Detect if the iframe content has loaded successfully

Javier Orellana picture Javier Orellana · Dec 28, 2010 · Viewed 68.1k times · Source

I have a widget that contains an iframe. The user can configure the url of this iframe, but if the url could not be loaded (it does not exists or the user does not have access to internet) then the iframe should failover to a default offline page.

The question is, how can I detect if the iframe could be loaded or not? I tried subscribing to the 'load' event, and, if this event is not fired after some time then I failover, but this only works in Firefox, since IE and Chrome fires the 'load' event when the "Page Not Found" is displayed.

Answer

RobinBrouwer picture RobinBrouwer · Jan 7, 2011

I found the following link via Google: http://wordpressapi.com/2010/01/28/check-iframes-loaded-completely-browser/

Don't know if it solves the 'Page Not Found' issue.

<script type="javascript">
var iframe = document.createElement("iframe");
iframe.src = "http://www.your_iframe.com/";
if (navigator.userAgent.indexOf("MSIE") > -1 && !window.opera) {
  iframe.onreadystatechange = function(){
    if (iframe.readyState == "complete"){
      alert("Iframe is now loaded.");
    }
  };
} else {
  iframe.onload = function(){
    alert("Iframe is now loaded.");
  };
}
</script>

I haven't tried it myself, so I don't know if it works. Good luck!