JS Event Listener within iFrame

4.2k views Asked by At

Hey I have the following code, which functions correctly how dealing with audio events, however this doesn't work within an iFrame:

var sounds = document.getElementsByTagName('audio');
/* Loop through the nodelist - this is **not** an array */
for(var i = 0; i < sounds.length; i++){
/* Get the item in your nodelist. This **is** an element. */
var sound = sounds.item(i);
/* Now add your event listener here - You can only add one at a 
 * time, though. So I decided to make the event a separate  
 * function and attach it multiple timers. */
function eventHandler(){
    document.title = document.title.replace('\u25B6', '')
    if (!sound.paused) {
        document.title = '\u25B6 ' + document.title.replace('\u25B6 ', '')
        return false;
    }
}
sound.addEventListener('play', eventHandler, false);
sound.addEventListener('pause', eventHandler, false);
sound.addEventListener('ended', eventHandler, false);
}

So I have used the following code, but this comes up with the error: "undefined is not a function (evaluating 'iframe.contentWindow.getElementsByTagName('audio')')"

var iframes = document.getElementsByTagName('iframe'); //all iframes on page
for(var i=0; i<iframes.length; i++){
var iframe = iframes.item(i);
var sounds = iframe.contentWindow.getElementsByTagName('audio');
/* Loop through the nodelist - this is **not** an array */
for(var i = 0; i < sounds.length; i++){
/* Get the item in your nodelist. This **is** an element. */
var sound = sounds.item(i);
/* Now add your event listener here - You can only add one at a 
 * time, though. So I decided to make the event a separate  
 * function and attach it multiple timers. */
function eventHandler(){
    document.title = document.title.replace('\u25B6', '')
    if (!sound.paused) {
        document.title = '\u25B6 ' + document.title.replace('\u25B6 ', '')
        return false;
    }
 }
}
    sound.addEventListener('play', eventHandler, false);
    sound.addEventListener('pause', eventHandler, false);
    sound.addEventListener('ended', eventHandler, false);
}
1

There are 1 answers

2
somethinghere On

I just did a little test and all you are missing is calling the getElementsByTagName function on the iFrames' document, as the contentWindow is the iFrames' window element (similar to the window element in your parent page).

You cannot use iFrames in code snippets here, so I can't show you an implementation, but this should work (it worked in my testing (although I tried it with loading CNN.com and counting the number of divs returned by getElementByTagName, and that worked):

var iframe = iframes.item(i);
iframe = iframe.contentWindow.document;
var sounds = iframe.getElementsByTagName('audio');

Keep in mind that content-origin restrictions apply here. If you did noit instantiate the iframe or its not on the same domain, errors can occur.