Chrome JavaScript Debugging: how to break when a value changes

后端 未结 3 1365
梦谈多话
梦谈多话 2020-12-14 10:48

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 con

相关标签:
3条回答
  • 2020-12-14 11:29

    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).

    0 讨论(0)
  • 2020-12-14 11:32

    Browser-implemented functions can't be null-ed! Technically speaking.

    If window.console.log funcion was assigned null, then just restore it deleting it!

    delete console.log
    

    That will do the job :)

    EDIT: That's not an answer to your main question, but I think your question is comming from you searching a way to debug, so this answer basically skips the need to detect var changes.

    0 讨论(0)
  • 2020-12-14 11:32

    You can't touch the console object... never, ever. The only thing that can happen is that a console variable is declared in a scope/namespace, other than the global scope, hiding the global console. You can still access it using window.console, though. Other than that, the only things I can think of that cause this are:

    • You've set the user agent in your console overrides to emulate a version of IE that doesn't support console
    • Your code is throwing an error because of some other problem with your code
    • As @alexandernst pointed out: you're overriding a property of the console object. Delete the method you're unable to access and you're fine

    To find out where you need to look in the code set conditional breakpoints and watch a couple of expressions, and use the pause on uncaught exceptions button

    0 讨论(0)
提交回复
热议问题