5

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.

user2521295
  • 823
  • 2
  • 12
  • 23
  • https://stackoverflow.com/a/37753146/2813224 upvote it if it helped. – zer00ne Feb 29 '20 at 04:45
  • I am using that and the error is resulting from iframe-resizer trying to be called when the iframe contents aren't loaded yet! – user2521295 Mar 05 '20 at 18:37
  • 1
    @user2521295 Someone left an answer below; did it solve what you asked? If you did see it, why didn't you respond to it somehow? They don't know if it worked or not, looks pretty good to me and well-written I might add. – Funk Forty Niner Mar 09 '20 at 22:47

1 Answers1

14

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).

Suboptimierer
  • 554
  • 4
  • 11
  • 1
    Thank you! This seems to have worked-- ended up running into a lot of X-frame options issues/security problems for the use case for which my client needed this functionality, but this indeed seemed to have fired at the correct time. Thank you! – user2521295 Mar 10 '20 at 20:10
  • Am I using this incorrectly? After embedding the new iFrame into a new embedded Div it opens the src. Then I plug the addEventListener "load" function into Chromes console. Then I change the href with an new url, ie, iframe.contentWindow.location.href = "https://yaddayaddayadda" - but i get nothing written to the console. So I change the command to alert and no alert occurs when the href is changed. I've heard that chrome replaces the iFrame first with an empty html page. Could that be why it isn't firing? Because the empty html page is loaded when the function checks? – John Muggins Jul 27 '21 at 16:37
  • It seems like it doesn't work. – yoty66 Jul 04 '23 at 21:25
  • Please check : https://stackoverflow.com/a/10444444/12624118 – yoty66 Jul 04 '23 at 21:25