捕获跨源iframe事件
我在域A有一个网站,其中包含用于显示video的iframe,该video在YouTube上托管。 在iframe加载事件中,我试图在iframe中注册keyup事件,以便在客户端按下转义键时关闭video。 以下是我的代码示例:
$(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.
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中注册事件?
同源策略阻止您这样做。
源由方案,端口,协议和域组成。 如果这些匹配,那么JavaScript可用于注册事件或操纵DOM。
如果您的网站是http://example.com
且video位于http://example.org
则无法跨域编写脚本,因为域名不匹配。
不同的来源可能会进行通信,但是他们都需要选择此function。 postMessage
就是这样一个JavaScript函数。 但是,由于您无法控制运行video的原点,因此无法帮助您。
解决方案可能是您在页面上内嵌显示video。 这应该使您能够捕获事件。