Javascript callback when IFRAME is finished loading?

FlySwat picture FlySwat · Oct 2, 2008 · Viewed 266.8k times · Source

I need to execute a callback when an IFRAME has finished loading. I have no control over the content in the IFRAME, so I can't fire the callback from there.

This IFRAME is programmaticly created, and I need to pass its data as a variable in the callback, as well as destroy the iframe.

Any ideas?

EDIT:

Here is what I have now:

function xssRequest(url, callback)
{
    var iFrameObj = document.createElement('IFRAME');
    iFrameObj.src = url;            
    document.body.appendChild(iFrameObj);   

    $(iFrameObj).load(function() 
    {
        document.body.removeChild(iFrameObj);
        callback(iFrameObj.innerHTML);
    });
}

This callsback before the iFrame has loaded, so the callback has no data returned.

Answer

Remy Sharp picture Remy Sharp · Oct 16, 2008

First up, going by the function name xssRequest it sounds like you're trying cross site request - which if that's right, you're not going to be able to read the contents of the iframe.

On the other hand, if the iframe's URL is on your domain you can access the body, but I've found that if I use a timeout to remove the iframe the callback works fine:

// possibly excessive use of jQuery - but I've got a live working example in production
$('#myUniqueID').load(function () {
  if (typeof callback == 'function') {
    callback($('body', this.contentWindow.document).html());
  }
  setTimeout(function () {$('#frameId').remove();}, 50);
});