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?
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.
Actually, yes you can.
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.
Reasons for failure could be:-
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With