Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding an event listener to an iframe

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?

like image 512
Ronald Avatar asked Sep 08 '09 14:09

Ronald


People also ask

Can I add event listener to iframe?

You can also add event listeners that will execute in response to certain player events, such as a player state change. This guide explains how to use the IFrame API. It identifies the different types of events that the API can send and explains how to write event listeners to respond to those events.

Can I add event listener to anchor tag?

Actually, yes you can.

Can you add an EventListener to a function?

The method addEventListener() works by adding a function, or an object that implements EventListener , to the list of event listeners for the specified event type on the EventTarget on which it's called.


3 Answers

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
like image 81
AnthonyWJones Avatar answered Nov 07 '22 21:11

AnthonyWJones


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.

like image 39
Mushex Antaranian Avatar answered Nov 07 '22 21:11

Mushex Antaranian


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.

like image 4
Brian Moeskau Avatar answered Nov 07 '22 20:11

Brian Moeskau