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.
In short, to check if a page is in an iframe, you need to compare the object's location with the window object's parent location. If they are equal, then the page is not in an iframe; otherwise, a page is in an iframe.
If you want to check if no page loaded inside iframe, and the iframe is not cross-domain you could check for the existence of the body tag inside of the iframe. If it exists, then something loaded. If the iframe is cross-domain, you will be blocked by the same-origin policy.
If you wish to check if there is any iframe at all, you could use getElementsByTagName('iframe'). To make live a little easier, you can take a look at jQuery. This is a Javascript library that helps you to create DOM objects and/or find them in the DOM tree.
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!
Nowadays the browsers have a series of security limitations that keep you away from the content of an iframe (if it isn´t of your domain).
If you really need that functionality, you have to build a server page that have to work as a proxy, that receive the url as a parameter, test if it is a valid url, and does the redirect or display the error page.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With