33

Is it possible, in any browser, using any plugin, to enable or disable breakpoints in your code programmatically?

I already know about setting conditional breakpoints, but I'm really interested in setting them via code.

nickf
  • 537,072
  • 198
  • 649
  • 721
  • 1
    Possible duplicate of [Set a javascript breakpoint in code - in chrome?](http://stackoverflow.com/questions/10050465/set-a-javascript-breakpoint-in-code-in-chrome) if only the title contained the keyword "code" SEO gods would have ruled otherwise :-) – Ciro Santilli OurBigBook.com May 31 '16 at 14:57

3 Answers3

30

First you could add a call to a function like __checkDebug(); which will check for a global (or semi-global) variable and when said variable is true, call debugger.

  
function __checkDebug() {
   if (debugme) debugger;
}

all of your functions you're concerned about debugging would be like so:

  
function foo() {
   __checkDebug();

   //.... whatever foo was gonna do.
}

You can then take it a little further and dynamically decorate functions while the code is being executed like so:


Function.prototype.debug = function(){   
   var fn = this; 
   return function(){     
       if (debugme) debugger; 
       return fn.apply(this, arguments);     
   }; 
}; 

foo = foo.debug();  

now any time foo is called it will call debugger if the debugme variable is truthy.

Another option would be to build a javascript build system that injects the call after every function declaration - this requires a syntax parser but if you're only looking to modify functions a simple tokenizer for that use case is pretty easy to write - but I'll leave that up to you.

Marcus Pope
  • 2,293
  • 20
  • 25
28

You can use debugger; in code to make breakpoint for firebug. For example:

alert('1');
debugger;
alert('2');

And firebug automatically stops on this keyword.

CoolEsh
  • 3,134
  • 1
  • 21
  • 24
1

Have a look at the FireBug functions debug(fn) & undebug(fn) names which set a breakpoint on the first line of the named function.

See point #6:

http://michaelsync.net/2007/09/30/firebug-tutorial-script-tab-javascript-debugging

Tramov
  • 1,166
  • 1
  • 11
  • 17
  • Can this be executed from the Javascript itself, or is it only from the firebug command line? Adding `debug(myFunctionName);` to my code throws an error for me. – nickf Mar 11 '11 at 12:25
  • The original website is no longer active. Most recent Wayback Machine snapshot from 2018: https://web.archive.org/web/20180412190544/http://michaelsync.net/2007/09/30/firebug-tutorial-script-tab-javascript-debugging – Jan Molak Dec 15 '20 at 22:55