捕获跨域iframe事件 [英] Capturing Cross-Origin iframe Events

查看:184
本文介绍了捕获跨域iframe事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在域A有一个网站,该网站包含用于展示视频的iframe,该网站托管在YouTube上.在iframe加载事件中,我尝试在iframe中注册keyup事件,以便当客户端按退出键时可以关闭视频.这是我的代码示例:

I have a website at domain A that contains an iframe used to show a video, which is hosted on YouTube. On the iframe load event, I am attempting to register for the keyup event in the iframe so I can close the video when a client presses the escape key. Here is an example of my code:

$(myIFrame).bind('load', function() {
    $(myIFrame.contentWindow.document).keyup(function(event) {
        console.log(event.keyCode);
    });
    alert('Event Registered');
});

我遇到以下例外情况:

Firefox:Error: Permission denied to access property "document"
Chrome:Uncaught SecurityError: Blocked a frame with origin "A" from accessing a frame with origin "https://www.youtube-nocookie.com". Protocols, domains, and ports must match.

Firefox: Error: Permission denied to access property "document"
Chrome: Uncaught SecurityError: Blocked a frame with origin "A" from accessing a frame with origin "https://www.youtube-nocookie.com". Protocols, domains, and ports must match.

是否可以在跨域iframe中注册事件?

Is there any way to register for events in a cross-origin iframe?

推荐答案

相同起源政策阻止您执行此操作.

起源由方案,端口,协议和域组成.如果这些匹配,则可以使用JavaScript来注册事件或操纵DOM.

An origin consists of a scheme, port, protocol and domain. If these match, then JavaScript can be used to register events or to manipulate the DOM.

如果您的站点位于http://example.com且视频位于http://example.org上,则由于域不匹配,将无法进行跨域脚本编写.

If your site is http://example.com and the video is on http://example.org then cross domain scripting will not be possible because the domains do not match.

不同来源可以进行通信,但是它们都需要选择使用此功能. postMessage 是一种这样的JavaScript函数.但是,由于您无法控制运行视频的来源,因此这里无济于事.

It is possible for different origins to communicate, however they both need to opt into this functionality. postMessage is one such JavaScript function. However as you have no control of the origin running the video it cannot help you here.

您可以选择在页面上直接内嵌视频.这应该使您能够捕获事件.

On solution for you may be to display the video inline on your page. This should enable you to capture events.

这篇关于捕获跨域iframe事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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