检查 iframe 内容是否已加载?

use*_*295 0 javascript iframe

当 iframe 的内容加载时,我需要触发一个 javascript 函数。我看到很多(过时的?)使用 iframe onload 事件的答案,这似乎根本没有触发(在 Chrome 中)。

根本不触发(至少在 Chrome 中):

<iframe id="target-iframe" src="SRC_URL" onload="iframeLoaded()"></iframe>
Run Code Online (Sandbox Code Playgroud)

在内容准备好之前为 iframe 的 readyState 设置一个监听器:

function listenForIframe() {
    const iframe = document.getElementById("target-iframe");
    var iframeDoc = iframe.contentDocument || iframe.contentWindow.document;

    // Check if loading is complete
    if (iframeDoc.readyState == 'complete') {
        iframe.contentWindow.onload = function(){
            // console.log('loaded')
        };
        iframeLoaded();
        return;
    }
    window.setTimeout(listenForIframe, 100);
}
Run Code Online (Sandbox Code Playgroud)

我当前的用例是使用 iframe-resizer 并收到以下错误消息,因为 iframe 内容尚不存在。只是想在这里保持一个干净的控制台!

iframeResizer.js:791 Failed to execute 'postMessage'on 'DOMWindow': The target origin ('http://localhost:3000')does not match the receiver window's origin ('null')

它最终会加载,但如果可能的话,希望摆脱该错误。

小智 6

要在 iFrame 加载时收到通知,您今天仍然可以使用 onload 事件。

创建 iFrame 并为 JavaScript 设置 ID:

<iframe id="test" src="SRC_URL"></iframe>
Run Code Online (Sandbox Code Playgroud)

现在使用 JavaScript 访问 iFrame 并为加载事件设置一个 EventListener:

const iframe = document.getElementById("test");
iframe.addEventListener("load", function() {
    console.log("Finish");
});
Run Code Online (Sandbox Code Playgroud)

当 iFrame 完成加载时,控制台中会记录“Finish”。我已经用谷歌浏览器测试过它,它工作正常。

在 EventHandler 中,您可以执行操作。例如,发送一条消息:

iframe.contentWindow.postMessage({ title: "Hi", message: "Seems to work" }, targetOrigin);
Run Code Online (Sandbox Code Playgroud)

还请确保您有权嵌入网页(X 框架选项)。