如何检查 iframe 是否已加载或是否有内容?

IT技术 javascript jquery iframe
2021-01-12 17:09:06

我有一个带有 id = "myIframe" 的 iframe,这里是我的代码来加载它的内容:

$('#myIframe').attr("src", "my_url");

问题是有时加载时间太长,有时加载速度很快。所以我必须使用“setTimeout”函数:

setTimeout(function(){
   if (//something shows iframe is loaded or has content)
   {
       //my code
   }
   else
   {
       $('#myIframe').attr("src",""); //stop loading content
   }
},5000);

我只想知道如何确定 iFrame 是否已加载或是否有内容。使用iframe.contents().find()将不起作用。我不能用iframe.load(function(){})

6个回答

试试这个。

<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();"> 
将字符串传递给 setTimeout() 的缺点。传递函数引用更简洁:setTimeout(checkIframeLoaded, 100);
2021-03-12 17:09:06
这是我试图完成的最佳解决方案。我在 iFrame 中使用了 AngularJS,并使用了 ng-include,这会延迟所包含文件的加载。我试图在 onload 事件上打印 Iframe 的内容,但它触发得太快了。检查readyState === "complete"成功了,因为在加载所有内容之前它不会改变。
2021-03-15 17:09:06
这导致“不安全的 JavaScript 尝试从具有 url2 的框架访问具有 URL url1 的框架,域、协议和端口必须匹配。”
2021-03-22 17:09:06
如果 iframe 来自另一个域,这将不起作用: VM29320:1 Uncaught DOMException: Blocked a frame with origin "http://localhost:9002" from accessing a cross-origin frame.
2021-03-23 17:09:06
我不得不说这也是唯一对我有用的解决方案。你不能相信 iframe 上的 load 事件,因为在大多数情况下它会在 IE11、Chrome 和 Edge 上立即触发,iframe.contentDocument.location.href显示为about:blank. 即使在 HTML 中直接指定srcfor ,这似乎也是正确iframe的。
2021-03-31 17:09:06

请使用:

$('#myIframe').on('load', function(){
    //your code (will be called once iframe is done loading)
});

随着标准的变化更新了我的答案。

这种方法根本不起作用,因为事件会立即触发,因为iframes 通常以 开头src="about:blank",即使src直接在 HTML 中指定或在将iframe节点添加到 DOM之前也是如此。我通过在 IE11、Chrome 和 Edge 上的紧密循环中轮询iframe' 来测试这一点contentDocument.location.href如果被构架的内容确实通过元标记或 javascript 重定向,它也不起作用。
2021-03-16 17:09:06

我遇到了同样的问题并添加到此,我需要检查 iframe 是否已加载,而不管跨域策略如何。我正在开发一个 chrome 扩展,它在网页上注入某些脚本并在 iframe 中显示来自父页面的一些内容。我尝试了以下方法,这对我来说很完美。
PS:就我而言,我确实可以控制 iframe 中的内容,但不能控制父站点上的内容。(iframe 托管在我自己的服务器上)

首先:
创建一个带有data-属性的 iframe,例如(在我的情况下,这部分在注入脚本中)
<iframe id="myiframe" src="http://anyurl.com" data-isloaded="0"></iframe>

现在在 iframe 代码中,使用:

var sourceURL = document.referrer;
window.parent.postMessage('1',sourceURL);



现在回到根据我的情况注入的脚本:

setTimeout(function(){
  var myIframe = document.getElementById('myiframe');
  var isLoaded = myIframe.prop('data-isloaded');
  if(isLoaded != '1')
  {
    console.log('iframe failed to load');
  } else {
    console.log('iframe loaded');
  }
},3000);


和,

window.addEventListener("message", receiveMessage, false);
function receiveMessage(event)
{
    if(event.origin !== 'https://someWebsite.com') //check origin of message for security reasons
    {
        console.log('URL issues');
        return;
    }
    else {
        var myMsg = event.data;
        if(myMsg == '1'){
            //8-12-18 changed from 'data-isload' to 'data-isloaded
            $("#myiframe").prop('data-isloaded', '1');
        }
    }           
}



它可能不能完全回答这个问题,但它确实是我通过这种方法解决的这个问题的一个可能情况。

@JohnK 感谢您指出这一点,我已经解决了。很高兴知道这对您有用。
2021-03-20 17:09:06
您的代码中存在一些错误,例如 document.getElement->s<-ById,但整个想法很有用。有用。谢谢)
2021-03-26 17:09:06

最简单的选择:

<script type="text/javascript">
  function frameload(){
   alert("iframe loaded")
  }
</script>

<iframe onload="frameload()" src=...>
不是一个可靠的解决方案,因为即使 url 损坏,它也会发出警报。
2021-03-12 17:09:06

您可以使用 iframe 的load事件在 iframe 加载时做出响应。

document.querySelector('iframe').onload = function(){
    console.log('iframe loaded');
};

这不会告诉您是否加载了正确的内容:要检查,您可以检查contentDocument.

document.querySelector('iframe').onload = function(){
    var iframeBody = this.contentDocument.body;
    console.log('iframe loaded, body is: ', body);
};

contentDocument如果 iframesrc指向与您的代码运行的域不同的域,检查将不起作用

请考虑编辑您的帖子,以添加更多关于您的代码的作用以及为什么它会解决问题的解释。大多数只包含代码(即使它正在工作)的答案通常不会帮助 OP 理解他们的问题。
2021-03-29 17:09:06