javascript中的Catch X-Frame-Options错误

Catch X-Frame-Options Error in javascript

本文关键字:错误 X-Frame-Options Catch 中的 javascript      更新时间:2023-09-26

从另一个域加载iframe时,是否有任何方法可以捕获错误。下面是jsfiddle中的一个例子。http://jsfiddle.net/2Udzu/。如果我收到错误,我需要显示一条消息。

以下是我想做的,但不起作用:

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

有人有什么想法吗?

onerror仅适用于脚本错误。帧内容错误检查必须使用任何其他方法进行。这里有一个例子。

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

由于跨域限制,无法检测页面是否成功加载,或者页面是否因客户端错误(HTTP 4xx错误)和服务器错误(HTTP 5xx错误)而无法加载。

如果父站点和iframe url都可以访问,那么知道页面已完全加载(没有"同源"问题)的一种方法是从子站点向父站点发送消息(postMessage),如下所示;

父站点(包含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);
};

子站点(iframe中的URL)

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

如果你想要多个来源的可能性,你可以通过使用像PHP这样的服务器端语言来获得the_origin_site.url


只有当你试图放入iframe的域与你请求的域相同时,接受的答案才有效——这个解决方案适用于你可以访问两个域上的脚本的跨域。

我使用以下代码来检测jquery 是否发生了x帧选项错误

$(iframe).load(function (e) {
  try
    {
    // try access to check
    console.log(this.contentWindow.document);
    // Access possible ...
    }
  catch (e)
    {
    // Could not access. Read out error type 
    console.log(e);
    var messageLC = e.message.toLowerCase();
    if (messageLC.indexOf("x-frame-options") > -1 || messageLC.indexOf('blocked a frame with origin') > -1 || messageLC.indexOf('accessing a cross-origin') > -1)
      {
      // show Error Msg with cause of cross-origin access denied
      }
    else
      {
      // Shoe Error Msg with other cause
      }
    }
});