加载iframe的内容时,我需要触发javascript函数。我看到许多使用iframe onload事件的(过时的?)答案,(在Chrome中)似乎根本没有触发。
完全不触发(至少在Chrome中):
<iframe id="target-iframe" src="SRC_URL" onload="iframeLoaded()"></iframe>
在内容准备就绪之前触发为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);
}
我当前的用例是使用iframe-resizer并收到以下错误消息,因为iframe内容尚不存在。只是想在这里保持干净的控制台!
iframeResizer.js:791无法在
'postMessage'
上执行'DOMWindow'
: 提供的目标原点('http://localhost:3000')
不匹配 收件人窗口的来源('null')
。
它最终会加载,但希望尽可能消除该错误。
答案 0 :(得分:4)
要在加载iFrame时收到通知,您今天仍然可以使用onload事件。
创建iFrame并为JavaScript设置ID:
<iframe id="test" src="SRC_URL"></iframe>
现在使用JavaScript访问iFrame并为load事件设置一个EventListener:
const iframe = document.getElementById("test");
iframe.addEventListener("load", function() {
console.log("Finish");
});
iFrame加载完成后,将在控制台中记录“完成”。我已经使用Google Chrome浏览器对其进行了测试,并且效果很好。
然后在EventHandler中可以执行操作。例如,发送一条消息:
iframe.contentWindow.postMessage({ title: "Hi", message: "Seems to work" }, targetOrigin);
还请确保您具有嵌入网页的权限(X框架选项)。