尝试从YouTube <iframe>捕获console.log消息

lin*_*iii 5 javascript youtube iframe

YouTube HTML5视频<iframe>会针对各种事件(如加载广告横幅)触发console.log消息.我正在尝试以编程方式使用JavaScript捕获console.log消息以触发函数,如下所示:

console['log'] = function(msg){
    // Operate on msg
}
Run Code Online (Sandbox Code Playgroud)

要向YouTube发送console.log消息<iframe>,可使用以下方法(以简写为参考):

document.getElementsByTagName('iframe')[youTubeIframe].contentWindow.console.log(msg);
Run Code Online (Sandbox Code Playgroud)

但是,以下代码不起作用:

document.getElementsByTagName('iframe')[youTubeIframe].contentWindow.console['log'] = function(msg){
    // Operate on msg from YouTube <iframe>
}
Run Code Online (Sandbox Code Playgroud)

我也尝试过:

window.console = document.getElementsByTagName('iframe')[youTubeIframe].contentWindow.console;
console['log'] = function(msg){
    // Operate on msg
}
Run Code Online (Sandbox Code Playgroud)

我不明白的是; 如果我能够向YouTube调用console.log消息<iframe>,那么如何捕获控制台日志消息?如果有这样的方法,这样做的正确方法是什么?

小智 3

在最新版本的浏览器上,您无法从与包含 iframe 的页面不同的域(即 Chrome v31、Firefox v26、IE11)访问 iFrame 内的任何元素。

它可以在某些特定浏览器的旧版本上运行,但这肯定无法跨浏览器运行。


当前符合W3C HTML5 嵌入内容(包括 iframe)规范的浏览器不仅强制执行同源策略,而且还接受新sandbox属性来指定对 iframe 的更多限制。

您可以在此页面中查看支持新标准的浏览器: http://html5test.com/compare/feature/security-sandbox.html

接受新属性的浏览器还必须遵守 W3C 同源策略,因此不会让您访问该console对象(或 iframe 内的任何其他对象)。