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

查看:77
本文介绍了向 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 框架添加我的侦听器,如下所示:

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天全站免登陆