9

这是从第三方库中提取的有罪片段:

function hasConsoleLogger() {
    return window.console && window.console.log;
}

没有什么花哨的,但它令人惊讶地返回: TypeError: Cannot read property 'console' of null

它在浏览器上下文 (Chrome) 中执行,因此不涉及 Node.js 非窗口内容。

我已经检查了潜在的恶意delete windowwindow = null没有成功。

发生此错误的应用程序使用友好 iFrame 和 document.write() 调用运行。

不幸的是,我无法提供该问题的任何演示链接。

所以我想我的问题是“如何在浏览器中错误地使窗口对象无效或无法访问?”

4

1 回答 1

4

当窗口关闭时,Chrome 首先设置window.consolenull,然后设置为window

window通过创建一个从不同上下文引用的函数,以下代码将可靠地重现错误:

var w = window.open('/');
// Using document.write to run code in the context of the other window
w.document.write('<script>opener.func = function(){return window;};</script>');
w.close();
// Naive timer to wait for Garbage collection
setTimeout(function() {
    console.log(func() === null); // true
}, 100);
于 2013-04-16T09:28:51.803 回答