10

Is it possible to add an event listener to an iframe? I've tried this code, but it doesn't seem to work:

document.getElementsByTagName('iframe')[0].contentWindow.window.document.body.addEventListener('afterLayout', function(){
                console.log('works');
            });

I've also just tried using getting the element by id and adding my listener via the JavaScript framework I'm using, like this:

Ext.fly("iframeID").addListener('afterLayout', function(){ alert('test'); });

I can call functions in the iframe, so I don't think security is an issue. Any ideas?

Ronald
  • 16,033
  • 9
  • 27
  • 29

3 Answers3

12

I never tried to handle 'afterLayout' event but for more browser compatible code you'll use (iframe.contentWindow || iframe.contentDocument) instead of iframe.contentWindow .

try something like

var iframe = document.getElementsByTagName('iframe')[0],
    iDoc = iframe.contentWindow     // sometimes glamorous naming of variable
        || iframe.contentDocument;  // makes your code working :)
if (iDoc.document) {
    iDoc = iDoc.document;
    iDoc.body.addEventListener('afterLayout', function(){
                        console.log('works');
                });
};

Hope it'll help.

Mushegh A.
  • 1,431
  • 12
  • 18
4

If you are doing serious iframe work in Ext, you should look into the ManagedIFrame user extension:

http://www.extjs.com/forum/showthread.php?t=40961

It features built-in events and cross-frame messaging, as well as many other benefits.

Brian Moeskau
  • 20,103
  • 8
  • 71
  • 73
3

Reasons for failure could be:-

  1. The URL to which the iframe is directed from a different domain as the container, hence code is prevented by cross-domain script blocking.
  2. The code is running before the frame content is loaded
AnthonyWJones
  • 187,081
  • 35
  • 232
  • 306
  • 1) Same domain. 2) Trying to attach in an onReady event, so the frame content should be ready. Just realized I successfully attached an event listener for load to the iframe, so now I'm really not sure why 'afterLayout' isn't working. Maybe it's a framework issue. – Ronald Sep 08 '09 at 14:26
  • I think "load" is one of the few events you can listen for early - almost by definition, since you can't properly wait until loading is done without attaching a "load" listener earlier! I found that if you're writing the iframe contents programmatically (e.g. via `srcdoc`) you always have to wait for the "load" event (or jQuery `load()`) before attaching other event listeners will work. – peterflynn Jan 14 '14 at 09:30