telexper
telexper

Reputation: 2441

Automatically reload an iframe if source page changes

I don't know what's wrong with my code, even if I change the content of the target file it still wont refresh the iframe.

<script type="text/javascript">
var page = 'data/apps/<? echo $_SESSION['name']; ?><? echo $_SESSION['last']; ?>App.html', lM;

function checkModified(){
   $.get(page, function(a,a,x){
      var mod = x.getResponseHeader('last-modified');
      if(lM != mod){
         lM = mod;
         document.getElementById("frame").src += "";
      }
   }
}

setInterval(checkModified, 5000); // every 5 seconds
</script>

What I want to achieve is when there are changes on the target page, the iframe will automatically reload itself so that the changes can be shown to the user. Both pages are located in the same domain.

Upvotes: 0

Views: 1413

Answers (1)

tagawa
tagawa

Reputation: 4611

Firstly, you had a missing closing bracket ")" at the end of the $.get method.

The main problem, though, was probably that your server is not sending proper Last-Modified headers. The server I tested on didn't send any, meaning mod is undefined. A workaround is to check for Content-Length instead. It's not ideal because an edited page doesn't necessarily change size, but it seems you're in control of the page so you could ensure you add an extra byte to force a refresh.

Here is your checkModified function updated which should work:

function checkModified() {
   $.get(page, function(a, b, x) {
      var mod = (x.getResponseHeader('Last-Modified')) ? x.getResponseHeader('Last-Modified') : x.getResponseHeader('Content-Length');
      if (lM != mod) {
         lM = mod;
         console.log('Fetched');
         document.getElementById("frame").src += "";
      }
   });
}

Upvotes: 2

Related Questions