How to refresh a iframe when the page changes? Wit

2019-09-18 17:07发布

问题:

Is it possible to refresh an iframe whenever the page changes? (The page within the iframe - not the page the iframe is on) I want to have an iframe show a page which is being developed, then whenever the page is changed/updated I want the iframe to refresh so it shows the newer version. Hope that makes sense. :P
Or would it be better to use something else instead of an iframe? Are iframes outdated now?

回答1:

Only because I find this interesting... using jQuery:

<iframe id="someiFrame"></iframe>

<script type="text/javascript">
var page = '/some/page/on/this/server.html', lM;

function checkModified(){
   $.get(page, function(a,a,x){
      var mod = x.getResponseHeader('last-modified');
      if(lM != mod){
         lM = mod;
         $('#someiFrame').attr('src', page);
      }
   }
}

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

That will poll the page every 5 seconds (incredibly wasteful but if it's on a local dev machine, so what?) and reload the iframe only when the page is updated :)

Note that the iFrame MUST be on the same domain as the parent page.



回答2:

Do you have access to the page that's being modified? If so, why not just add a refresh meta tag to the page's HEAD that will then update your iframe at whatever interval you set. The following tag produces a 5-minute refresh and it won't matter if your iframe is cross domain:

  <meta http-equiv="refresh" content="300" />