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

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

问题描述

我在域 A 有一个网站,其中包含用于显示托管在 YouTube 上的视频的 iframe.在 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:错误:访问属性文档"的权限被拒绝
Chrome:未捕获的安全错误:阻止了一个来源为A"的框架访问来源为https://www.youtube-nocookie.com"的框架.协议、域和端口必须匹配.

有没有办法在跨域 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天全站免登陆