views:

3112

answers:

4

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?

A: 

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
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
+4  A: 

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.

bmoeskau
I would also go with this.
Manny Calavera
+1  A: 

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.

Mushex Antaranian
A: 

I have the same problem with attaching events to an iframe element.

Attaching event listener to document.body ,

document.body.onmousemove=function(){doSomething()}

or attaching event listener to a iframe

iframe.onmousemove=function(){doSomething()}

, has no reaction over the iframe.

The event registers, but fires only in Opera.

alfy