YouTube HTML5视频<iframe>
会针对各种事件(例如广告横幅的加载)触发console.log消息。我正在尝试使用JavaScript以编程方式捕获console.log消息,以触发如下功能:
console['log'] = function(msg){
// Operate on msg
}
要将console.log消息发送到YouTube
<iframe>
,可以使用以下方法(长期供引用):document.getElementsByTagName('iframe')[youTubeIframe].contentWindow.console.log(msg);
但是,以下代码不起作用:
document.getElementsByTagName('iframe')[youTubeIframe].contentWindow.console['log'] = function(msg){
// Operate on msg from YouTube <iframe>
}
我也尝试过:
window.console = document.getElementsByTagName('iframe')[youTubeIframe].contentWindow.console;
console['log'] = function(msg){
// Operate on msg
}
我不明白的是如果我能够向YouTube
<iframe>
调用console.log消息,那么如何捕获控制台日志消息?如果有的话,正确的方法是什么? 最佳答案
在最新版本的浏览器上,您无法从与包含iframe的页面不同的域(即Chrome v31,Firefox v26,IE11)访问iFrame中的任何元素。
它可以在某些特定浏览器的旧版本上运行,但是肯定不能跨浏览器运行。
当前符合W3C HTML5 embedded content (including iframes) specification的浏览器不仅执行同源策略,而且接受新的sandbox
属性来为iframe指定更多限制。
您可以在此页面中看到支持新标准的浏览器:
http://html5test.com/compare/feature/security-sandbox.html
接受新属性的浏览器还必须遵守W3C同源政策,因此将不允许您访问console
对象(或iframe中的任何其他对象)。