Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 707
kiewic Avatar asked Oct 23 '17 05:10

kiewic


People also ask

Can you breakpoint JavaScript?

In the debugger window, you can set breakpoints in the JavaScript code. At each breakpoint, JavaScript will stop executing, and let you examine JavaScript values. After examining values, you can resume the execution of code (typically with a play button).

How do you set a breakpoint within your code?

It's easy to set a breakpoint in Python code to i.e. inspect the contents of variables at a given line. Add import pdb; pdb. set_trace() at the corresponding line in the Python code and execute it. The execution will stop at the breakpoint.


1 Answers

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'));
like image 115
Nick stands with Ukraine Avatar answered Nov 14 '22 21:11

Nick stands with Ukraine