iFrame中的JS事件监听器

时间:2015-06-11 08:29:50

标签: javascript jquery events iframe event-listener

嘿,我有以下代码,它正确地处理音频事件的处理方式,但是这在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);
}

所以我使用了以下代码,但这会出现错误:&#34; undefined不是一个函数(评估&#39; iframe.contentWindow.getElementsByTagName(&#39; audio&#39;)& #39)&#34;

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 个答案:

答案 0 :(得分:0)

我刚刚进行了一些测试,您只需在iFrames getElementsByTagName上调用document函数,因为contentWindow是iFrames'window元素(类似于父页面中的window元素)。

你不能在这里的代码片段中使用iFrame,所以我不能向你展示一个实现,但这应该有用(它在我的测试中起作用(虽然我尝试加载CNN.com并计算{{1)的数量由div返回,并且有效):

getElementByTagName

请注意 var iframe = iframes.item(i); iframe = iframe.contentWindow.document; var sounds = iframe.getElementsByTagName('audio'); 限制适用于此处。如果您没有实例化iframe或它不在同一个域上,则可能会发生错误