Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeError: Cannot read property 'console' of null

Tags:

javascript

Here's the guilty snippet extracted from a third party lib :

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

Nothing fancy, but it surprisingly returns : TypeError: Cannot read property 'console' of null

It's executed in a browser context (Chrome) so no Node.js non-window stuff involved.

I've checked for potential malicious delete window or window = null without success.

The application where this bug occurs runs with Friendly iFrames, and document.write() calls.

Unfortunately I can't provide any demo link of the issue.

So I guess my question is "How could the window object be nullified or unreachable by mistake in a browser?"

like image 618
Delapouite Avatar asked Apr 16 '13 09:04

Delapouite


1 Answers

When a window is closed, Chrome first sets window.console is to null, then window.

The following code will reliably reproduce the error, by creating a function which references window from a different context:

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);
like image 87
Rob W Avatar answered Oct 20 '22 16:10

Rob W