将"DOMContentLoaded"事件附加到iframe上?

6

我创建了一个iframe,它应该在函数运行后继续重新加载。该函数读取iframe中的信息。目前我有这样的代码(有效):

function loaded(){
    alert(iframe.contentDocument.getElementsByClassName("blah")[0].innerHTML);
    iframe.src = filePath; //reloads the iframe
}

iframe.onload = loaded;

因为我希望它能更快地执行,所以这样做是否可行:当iframe加载DOM后,函数立即运行;

function loaded(){
    alert(iframe.contentDocument.getElementsByClassName("blah")[0].innerHTML);
    iframe.src = filePath; //reloads the iframe
}

iframe.addEventListener("DOMContentLoaded", loaded, false);

1
目前还没有可靠的跨浏览器解决方案。 - lonesomeday
2个回答

3

您最好使用消息传递 API

从您的<iframe>文档中,您可以向其parent发送一条消息,告诉它DOM已加载。

const iframe = document.getElementById( 'iframe' );
// set up the event handler on main page
window.addEventListener( 'message', (evt) => {
  if( evt.source === iframe.contentWindow) {
    console.log( evt.data );
  }
} );
iframe.onload = (evt) => console.log( 'onload' );

// For the snippet, we'll load the iframe document from a Blob
const iframe_document = new Blob( [`
<script>
  document.addEventListener( 'DOMContentLoaded', (evt) => {
    // tell the parent window we are ready
    parent.postMessage( 'DOM loaded', '*' );
  });
<\/script>
<h1>Hello world</h1>
<img src='https://i.picsum.photos/id/13/500/300.jpg?${Math.random()}' style="border:1px solid">
`], { type: "text/html" } );
iframe.src = URL.createObjectURL( iframe_document );
<iframe id="iframe" width="520" height="500"></iframe>


0
iframe.onreadystatechange = () => {
    if (iframe.readyState === "interactive") {
        // your code here
    }
};

我知道这是一个非常古老的问题,但是当我在寻找解决方法时,使用谷歌搜索到了这个。


iframe 是一个 HTML <iframe>,并且在 HTMLIFrameElement 原型上没有 onreadystatechange 属性。 - Kaiido
@Kaiido 也许他们是指 iframe.contentDocument.onreadystatechange - Nanoo
@Nanoo 但这不是他们写的,如果他们可以访问 iframe.contentDocument,那么他们可以直接从那里附加 DOMContentLoaded 事件监听器,但他们不能,因为在 iframe 加载之前,您无法访问 contentDocument -> 回到原点。 - Kaiido
@Kaiido iframe.contentDocument 不会触发 DOMContentLoaded 事件。 - Nanoo
@Nanoo...我在哪里说它会呢?我说它不会触发onreadystatechange事件。你说他们可能是指iframe.contentDocument,我说如果他们有访问iframe.contentDocument的权限,他们可以直接将DOMContentLoaded事件附加到其中,但是他们无论如何都无法访问此contentDocument,这就是问题的全部意义所在。 - Kaiido

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接