将事件侦听器添加到iframe中 [英] Adding an event listener to an iframe

查看:102
本文介绍了将事件侦听器添加到iframe中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可以向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');
            });

我刚刚尝试使用通过id获取元素,并通过JavaScript框架添加我的监听器'm using,like this:

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'); });

我可以调用iframe中的函数,所以我不认为安全是一个问题。有任何想法吗?

I can call functions in the iframe, so I don't think security is an issue. Any ideas?

推荐答案

我从来没有尝试处理'afterLayout'事件,但是更多的浏览器兼容代码
你会使用( iframe.contentWindow || iframe.contentDocument )而不是 iframe.contentWindow

I never tried to handle 'afterLayout' event but for more browser compatible code you'll use (iframe.contentWindow || iframe.contentDocument) instead of iframe.contentWindow .

尝试像

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');
                });
};

希望会有所帮助。

这篇关于将事件侦听器添加到iframe中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆