Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if iframe is ready to be written to

A 3rd party script on my web page creates an iframe. I need to know when this iframe is ready, so I can manipulate its DOM.

I can think of a hacky approach: repeatedly try to modify the iFrame's DOM, and return success when a change we make sticks between two attempts. For this to work, I would prefer a property I can check on the iframe repeatedly.

Is there an alternative, cross-browser evented approach to knowing that the iframe is ready? E.g. can we redefine the onLoad function to call into our code (but I don't know if I can do this, since I didn't create the iframe).

like image 926
Bilal and Olga Avatar asked Dec 21 '25 04:12

Bilal and Olga


2 Answers

using jquery?

function callIframe(url, callback) {
    $(document.body).append('<IFRAME id="myId" ...>');
    $('iframe#myId').attr('src', url);

    $('iframe#myId').load(function() 
    {
        callback(this);
    });
}

Question answered in jQuery .ready in a dynamically inserted iframe

like image 136
mythz Avatar answered Dec 22 '25 18:12

mythz


Have a variable in the parent:

var setToLoad = false;

Follow it up with a function to set it:

function SetToLoad() {
    setToLoad = true;
}

Then in the child iframe call this function using the window.opener

function CallSetToLoad() {
    window.opener.SetToLoad();
}

window.onload = CallSetToLoad;

This won't run until the iframe is finished loading, and if it's in the same domain it'll allow access to the opener. This would require editing a small portion of the 3rd party script.

EDIT: Alternative solution

Given that you can't edit the script, you might try something like:

frames["myiframe"].onload = function()
{
    // do your stuff here
}
like image 45
Joel Etherton Avatar answered Dec 22 '25 18:12

Joel Etherton



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!