Catch X-Frame-Options Error in javascript

拥有回忆 提交于 2019-11-30 15:07:50

问题


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

Here is what I would like to do, but it doesn't work:

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

Anyone have any ideas?


回答1:


The onerror is applicable only for script errors. Frame content error checking must be done using any other method. Here's 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 cross domain restriction, there's no way to detect whether a page is successfully loaded or if the page can't be loaded due to client errors (HTTP 4xx errors) and server errors (HTTP 5xx errors).




回答2:


If both the parent site and the iframe-url is accessible by you, a way to know that the page is fully loaded (without "sameorigin" issues) is sending a message (postMessage) from the child to the parent like this;

Parent site (containing the 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);
};

Child site (URL from the iframe)

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

You could get the_origin_site.url by using a server-side language like PHP if you want the possibility for multiple origins


The accepted answer only works if the domain you're trying to put in an iframe is the same as the one you're requesting from - this solution works for cross-domain where you have access to the scripts on both domains.



来源:https://stackoverflow.com/questions/12062081/catch-x-frame-options-error-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!