捕获跨源 iframe 事件

Capturing Cross-Origin iframe Events

我在域 A 中有一个网站,其中包含用于显示托管在 YouTube 上的视频的 iframe。在 iframe 加载事件中,我试图在 iframe 中注册 keyup 事件,以便在客户端按下转义键时关闭视频。这是我的代码示例:

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

我遇到以下异常:

火狐浏览器: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 中注册事件吗?

Same Origin Policy 阻止您这样做。

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

如果您的站点是 http://example.com 并且视频在 http://example.org 上,则跨域脚本将无法实现,因为域不匹配。

不同的来源可以进行通信,但是他们都需要选择加入此功能。 postMessage 就是这样一个 JavaScript 函数。但是,由于您无法控制来源 运行 视频,因此无法在此处为您提供帮助。

您的解决方案可能是在您的页面上内联显示视频。这应该使您能够捕获事件。