【问题标题】:Get response status code of cross domain iframe?获取跨域 iframe 的响应状态码?
【发布时间】:2015-07-23 09:21:37
【问题描述】:

我的网站上有一个 iframe,它指向第 3 方页面(即不在我的域上,我对其服务器没有任何控制权)。

我希望能够检查他们的网站是否在 iframe 中正确加载。在某些情况下 -

  • 它被某些防火墙阻止
  • 他们的服务中断了。

这样我就可以在这种情况下在 iframe 中显示正确的错误消息。我希望我能以某种方式找出 iframe 的响应状态代码。我怎样才能实现这样的目标?

【问题讨论】:

  • 您是否尝试使用AJAX 请求将数据加载到div 而不是iframe
  • 您的意思是对第 3 方页面的 AJAX 请求?
  • $( "#result" ).load( "ajax/test.html", function() { alert( "Load was performed." ); });
  • 加载ajax/test.html有什么用。我所说的页面在另一个域上,将受到同源策略的限制。
  • 将您的 URL 放到另一个域中,而不是“ajax/test.html”。

标签: javascript iframe cross-domain


【解决方案1】:

试试这个。

<script>
function checkIframeLoaded() {
    // Get a handle to the iframe element
     iframe = document.getElementById('your_iframe');

    var iframeDoc = iframe.contentDocument || iframe.contentWindow.document;

    // Check if loading is complete
    if (  iframeDoc.readyState  == 'complete' ) {

        iframe.contentWindow.onload = function(){
            alert("I am loaded");
        };

        // The loading is complete, call the function we want executed once the iframe is loaded
        afterLoading();
        return;
    } 

    // If we are here, it is not loaded. Set things up so we check   the status again in 100 milliseconds
    window.setTimeout('checkIframeLoaded();', 100);
}

function afterLoading(){
    alert("I am here");
}
</script>

<body onload="checkIframeLoaded();"> 

【讨论】:

  • 我怀疑你能否在 iframe 上获得 .contentDocument,因为相同的来源限制。
猜你喜欢
  • 1970-01-01
  • 2016-02-07
  • 2017-09-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-15
  • 1970-01-01
  • 2011-07-17
相关资源
最近更新 更多