Search code examples
javascriptjavascript-debugger

How to set a breakpoint in standard/native JavaScript functions?


Can I set a breakpoint on a standard JavaScript function? For example, can I pause the debugger every time context.beginPath() is called? Or every time that String.replace() is called?

UPDATE: What I meant by standard JavaScript function is functions built-in into the JavaScript engines.


Solution

  • Yes you can do this by overriding the original functionality by performing the following two steps:

    Make a copy(reference really) of the original function:

    mylog = console.log;
    

    Override the original with your copy inserting the debugger statement:

    console.log = function(){
        debugger;
        mylog.apply(this, arguments);
    }
    

    Now when called console.log will perform a breakpoint. (Note you'll have to handle different function arguments differently depending on the function be overriden)

    Here is another example using an instance methods, for example String.prototype.replace:

    let originalFunction = String.prototype.replace;
    String.prototype.replace = function(...args) {
        debugger;
        return originalFunction.call(this, ...args);
    }
    
    console.log('foo bar baz'.replace('bar', 'BAR'));