Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chrome JavaScript Debugging: how to break when a value changes

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.

like image 572
Janik Zikovsky Avatar asked Nov 08 '12 15:11

Janik Zikovsky


1 Answers

The answer below doesn't work for window.console because console (like other browser-native environment variables) is treated specially. Any attempt to assign a value to console only "covers up" the original value; it does not replace it. You can't detect when the console value changes, but you can delete window.console to restore the original environment-supplied value.

For other values, use Object.defineProperty to define a custom setter for some global window.foobar. The setter function runs whenever window.foobar is assigned a new value:

(function() {
    var actualFoobar = window.foobar;

    Object.defineProperty(window, "foobar", {
        set: function(newValue) {
            if(newValue === null) { 
                alert("someone is clobbering foobar!"); // <-- breakpoint here!
            }

            // comment out to disallow setting window.foobar
            actualFoobar = newValue;
        },

        get: function() { return actualFoobar; }
    });

})();

Then, put a breakpoint in that setter function.

This approach will work for global variables or any object property (simply change window to the object that has the property).

like image 168
apsillers Avatar answered Sep 19 '22 19:09

apsillers