获取跨域iframe的响应状态代码?

时间:2022-10-18 09:28:08

I have a iframe on my website which points to 3rd party page (i.e. Not on my domain and I don't have any control on their server).

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

I want to be able to just check if their website is being loaded properly inside the iframe or not. There can be cases where -

我希望能够检查他们的网站是否在iframe内正确加载。可能有以下情况 -

  • it gets blocked by some firewall
  • 它被某些防火墙阻止了

  • their service is down or something.
  • 他们的服务有所下降。

So that I can show a proper error message inside the iframe in that case. I was hoping that I can find out the iframe's response status code somehow. How can I achieve something like this?

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

1 个解决方案

#1


Try this.

<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();"> 

#1


Try this.

<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();">