18910140161

iframe src 什么功能:判断iframe的src是否生效?

顺晟科技

2022-09-27 07:14:49

224

在Vue中嵌套iframe标签用来展示其他外部网页(例如:https://www.baidu.com/?tn=390...),有的网页由于同源策略或其他原因不能显示页面。请问如何判断这个外部网页能不能显示?

try this

<script>
function checkIframeLoaded() {
    // Get a handle to the iframe element
    var iframe = document.getElementById('i_frame');
    var iframeDoc = iframe.contentDocument || iframe.contentWindow.document;

    // Check if loading is complete
    if (  iframeDoc.readyState  == 'complete' ) {
        //iframe.contentWindow.alert("Hello");
        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();"> 

根据上面链接的问题,另外一个回答的一段代码中提到访问 contentDocument,似乎会涉及到跨域错误,值得关注。

var iframe = document.getElementsByTagName('iframe')[0];
console.log(iframe.contentDocument);

经过我自己的测试,会抛出下面的异常

Uncaught DOMException: Blocked a frame with origin "null" from accessing a cross-origin frame.
相关文章
我们已经准备好了,你呢?
2024我们与您携手共赢,为您的企业形象保驾护航