Ian Moore
Ian Moore

Reputation: 33

JavaScript Reload Function Not Working Properly

On my webpage I have a piece of JavaScript to reload/refresh an iframe every three seconds.

window.setInterval(function() {
      reloadIFrame()
  }, 3000);

  function reloadIFrame() {
    var frame = document.getElementById("iframe");
    var len = frame.getElementsByTagName("TABLE").length;
    if ( len == 0 ){
      console.log('reloading..');
      document.getElementById('iframe').contentWindow.location.reload();
    }
  }

However, I don't want the function to work when there is a table present in the iframe, and it still runs when there is a table. Please let me know if there is something I am missing or your suggestions for alternative solutions.

(I do believe that the iframe which I am referencing is local on localhost:8000. I'm working with Django, if that matters, and this is part of a template.)

Upvotes: 0

Views: 424

Answers (1)

Ian Moore
Ian Moore

Reputation: 33

For anyone with a similar problem:

As in charlietfl's comments on the original post, the contentWindow was not being referenced. My code as modified below works now:

window.setInterval(function() {
      reloadIFrame()
  }, 3000);

  function reloadIFrame() {
    var frame = document.getElementById("iframe");
    var len = frame.contentWindow.document.getElementsByTagName("TABLE").length;
    if ( len == 0 ){
      console.log('reloading..');
      document.getElementById('iframe').contentWindow.location.reload();
    }
  }

I simply needed to add contentWindow.document after frame.

Upvotes: 2

Related Questions