开发者

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 su开发者_JAVA技巧ccess 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).


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


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
}


Can you inject arbitrary scripting code into your iframe? If so, you should be able to make it so that some code executes in the iframe upon the the iframe loading that calls code in the parent page.


First: You probably won't be able to manipulate its dom when it loads html from other domain

And You probably are interested in DOMready. Look here: jQuery .ready in a dynamically inserted iframe


Bilal,

There's a document.readyState property that you can check (works in IE).

foo(){
 if([your iframe id].document.readyState != "complete")
 {
   setTimeout("foo()", 500); //wait 500 ms then call foo
 }
 else
 {
   //iframe doc is ready
 }
}

Arkady

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜