Search code examples
javascriptiframerefreshsession-storage

Refreshing multiple iframes


I have a page with several iframes. The iframes are grabbing jpeg images from security cams. I want the iframes to refresh every 7 seconds but then timeout after 40 refreshes. I am using sessionstorage for my counter. Here is what I have built so far. However the iframes are not refreshing.

<title>Oak Sec Cams (low-rez)</title>
<center><font color ="blue"> Oakland Security Cams (<b>Medium</b> / <a  href="tiny.html">Small</a>)</center>
<script type="text/javascript">

var intervalID = 0;

var iframes = document.getElementsByTagName("iframe");

function windowOnInitialize()
{
intervalID = setInterval(reloadiframes, 7000);
window.sessionStorage.setItem("intervalID", intervalID); 
//alert("we were called");
}

var counter = 0;

function reloadiframes()
{ 
var refreshCounter = window.sessionStorage.getItem("counter");
//alert(refreshCounter);
if (refreshCounter < 40)
{
    refreshCounter++;
    window.sessionStorage.setItem("counter", refreshCounter);
    location.reload();
    //alert(counter);


}
else
{

  clearInterval(intervalID);
window.sessionStorage.clear();

}
}

</script>

Solution

  • So the reason your iframes are not being refreshed every 7 seconds is that you haven't actually called the function anywhere in your code.

    function windowOnInitialize() {
      intervalID = setInterval(reloadiframes, 7000);
      window.sessionStorage.setItem("intervalID", intervalID); 
    }
    

    While you have defined the windowOnInitialize function you need to add this line to the bottom of your script

    windowOnInitialize()
    

    Also, the reload iframes function won't work due to the usage of "location.reload();". It will reload the current document, which is, in this case, the holder of the iframes. What you'll need is some sort of an iteration over the iframe elements that will reload each one individually. Hope this gets you on the right path:

     function reloadiframes() {
        var refreshCounter = window.sessionStorage.getItem("counter");
        if (refreshCounter < 40) {
            refreshCounter++;
            window.sessionStorage.setItem("counter", refreshCounter);
            for (var i = 0; i < iframes.length; i++) {
               iframes[i].src = iframes[i].src ; 
            }
        }
        else {
            clearInterval(intervalID);
            window.sessionStorage.clear();
        }
    }
    windowOnInitialize()