I am debugging a large JavaScript code base where, at some point, the “console” variable gets nulled when refreshing the page.
Is there a way to set a watch on console and make JavaScript break execution when that value changes (or when a condition (console == null) is true)?
I am using Chrome on Windows 7.
The answer below doesn’t work for
window.consolebecauseconsole(like other browser-native environment variables) is treated specially. Any attempt to assign a value toconsoleonly “covers up” the original value; it does not replace it. You can’t detect when theconsolevalue changes, but you candelete window.consoleto restore the original environment-supplied value.For other values, use
Object.definePropertyto define a custom setter for some globalwindow.foobar. The setter function runs wheneverwindow.foobaris assigned a new value:Then, put a breakpoint in that setter function.
This approach will work for global variables or any object property (simply change
windowto the object that has the property).