将“ DOMContentLoaded附加到iframe吗?

问题描述 投票:4回答:2

所以我创建了一个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);
javascript dom iframe
2个回答
1
投票
iframe.onreadystatechange = () => {
    if (iframe.readyState === "interactive") {
        // your code here
    }
};

我知道,这是一个非常老的问题,但是当我在寻找解决此问题的方法时,使用Google我找到了这个问题


0
投票

您所能做的最好是使用Messaging API

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>
© www.soinside.com 2019 - 2024. All rights reserved.