Catch X-Frame error in javascript

Is there a way to catch an error while loading an iframe from another domain. Here is an example in jsfiddle. http://jsfiddle.net/2Udzu/ I need to show a message if I get an error.

Here is what I would like to do, but this does not work:

$('iframe')[0].onerror = function(e) { alert('There was an error loading the iFrame'); } 

Does anyone have any idea?

+8
javascript html javascript-events dom-events error-handling
source share
2 answers

onerror applicable only for script errors. Frame error checking should be performed using any other method. Here is one example.

 <script> function chkFrame(fr) { if (!fr.contentDocument.location) alert('Cross domain'); } </script> <iframe src="http://www.google.com/" onload="chkFrame(this)"></iframe> 

Due to the cross-domain restriction, it is not possible to determine if the page loaded successfully, or if the page cannot be loaded due to client errors (HTTP 4xx errors) and server errors (HTTP 5xx errors).

+5
source share

If both the parent site and the iframe URL are available for you to find out that the page is fully loaded (no problem with "sameorigin"), send a message ( postMessage ) from the child to the parent like this;

Parent site (containing iframe)

 //Listen for message window.addEventListener("message", function(event) { if (event.data === "loading_success") { //Yay } }); //Check whether message has come through or not iframe_element.onload = function () { //iframe loaded... setTimeout(function() { if (!iframeLoaded) { //iframe loaded but no message from the site - URL not allowed alert("Failure!"); } }, 500); }; 

Sub site (URL from frame)

 parent.postMessage("loading_success", "https://the_origin_site.url/"); 

You can get the_origin_site.url using a server language such as PHP if you need the multi-origin feature


The accepted answer only works if the domain you are trying to insert in the iframe matches the one you are requesting - this solution works for a cross-domain domain where you have access to scripts in both domains.

0
source share

All Articles