Checking if iframe contents are loaded?

Viewed 10641

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.

1 Answers

To be notified when the iFrame is loaded, you can still use the onload event today.

Create the iFrame and set an ID for JavaScript:

<iframe id="test" src="SRC_URL"></iframe>

Now access the iFrame with JavaScript and set an EventListener for the load event:

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

When the iFrame has finished loading, "Finish" is logged in the console. I have tested it with Google Chrome and it works fine.

Within the EventHandler you can then perform actions. For example, send a message:

iframe.contentWindow.postMessage({ title: "Hi", message: "Seems to work" }, targetOrigin);

Please also make sure that you have permission to embed the web page (X-frame options).

Related