【问题标题】:Catch X-Frame-Options Error in javascript在 javascript 中捕获 X-Frame-Options 错误
【发布时间】:2012-08-17 05:23:41
【问题描述】:

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

这是我想做的,但它不起作用:

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

有人有什么想法吗?

【问题讨论】:

    标签: javascript html error-handling dom-events


    【解决方案1】:

    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 错误)而无法加载。

    【讨论】:

    • 我就是这么想的。只是想看看是否有人找到解决方法。我会在今天结束前接受你的回答。
    • onload 事件处理程序在 Safari 中不起作用,请参阅jeffdoubleyou.com/bin/view/Blog/JQueryDetectWhenIFrameLoaded 了解解决方法。
    • 我得到 fr.contentDocument 等于 null 即使该网站不是跨域
    【解决方案2】:

    如果您可以访问父站点和 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 的网址)

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

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


    仅当您尝试放入 iframe 的域与您请求的域相同时,接受的答案才有效 - 此解决方案适用于您可以访问两个域上的脚本的跨域。

    【讨论】:

      【解决方案3】:

      我正在使用以下代码来检测是否发生了 x-frame-option 错误或使用 jquery 发生的另一个错误

      $(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
            }
          }
      });
      

      【讨论】:

      • 这在跨域场景下是行不通的,至少在 Chrome 94 中不行。
      猜你喜欢
      • 2014-05-10
      • 1970-01-01
      • 2018-05-27
      • 1970-01-01
      • 2015-12-04
      • 2019-10-15
      • 1970-01-01
      • 2018-06-27
      • 2013-05-10
      相关资源
      最近更新 更多