I need to fire a javascript function when the contents of an iframe load. I'm seeing a lot of (outdated?) answers to use iframe onload event, which doesn't seem to be firing at all (in Chrome).
Doesn't fire at all (at least in Chrome):
<iframe id="target-iframe" src="SRC_URL" onload="iframeLoaded()"></iframe>
Setting up a listener for the readyState of the iframe fires before content is ready:
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);
}
My current use case is in using iframe-resizer and getting the following error message because the iframe contents do not exist yet. Just trying to keep a clean console here!
iframeResizer.js:791 Failed to execute
'postMessage'
on'DOMWindow'
: The target origin provided('http://localhost:3000')
does not match the recipient window's origin('null')
.
It eventually loads but would love to get rid of that error if possible.