繁体   English   中英

动态创建一个 iframe 并为其附加 onload 事件

[英]Dynamically create an iframe and attach onload event to it

我动态创建了一个 iframe 并为其添加了一个src属性。 然后我将此 iframe 附加到页面正文。 知道我要给iframe附加一个onload事件来读取iframe的内容。 有人可以建议我该怎么做吗?

frame = document.createElement('iframe');
frame.setAttribute('src','http://example.com');
body.appendChild(frame);
frame.onload = function(){
    alert('hi'); // here I want to read the content in the frame.
}

有些浏览器确实有 iframe 的 onload 事件,首先你应该在设置 iframe 的 src 属性之前尝试附加它。

我会避免完全使用它,因为在某些浏览器中它可能不会在某些条件下触发(例如目标在 IE 的缓存中)。

您可以使用计时器来检查框架的 contentWindow 的就绪状态是否完成

var inter = window.setInterval(function() {
    if (frame.contentWindow.document.readyState === "complete") {
      window.clearInterval(inter);
      // grab the content of the iframe here
    }
}, 100);

您可以向 iframe 的contentWindow添加一个load事件侦听器,就像任何其他Window 一样

这是一个 例子

      iframe = document.createElement('iframe')
      iframe.setAttribute('src', 'https://example.com/')

      document.getElementsByTagName('body')[0].appendChild(iframe)
      const onLoaded = function() {
        console.log('iframe loaded');
      }
      if (iframe.contentWindow.document.readyState === 'complete') {
        console.log('already loaded')
        onLoaded()
      } else {
        iframe.contentWindow.addEventListener('load', onLoaded)
      }

我刚刚试过这个并且它在 Chrome 中工作:

var iframe = document.createElement('iframe');
// append iframe to DOM however you like then:
iframe.contentWindow.parent.location.href // properly gives parent window's href.

W3school 表示所有主流浏览器都支持contentWindow

我怀疑您是否可以将 onload 事件附加到 iframe。它不适用于所有浏览器。 另一方面,您可以检查 iframe 是否由以下方式加载:

window.onload=function()
{
var iframe=document.getElementById('myframe');
if(iframe) 
    alert('The iframe has just been loaded.');
}

或者使用 AJAX 加载容器中的内容。 使用 AJAX,您可以设置适当的加载完成事件。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM