最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to check if 'debugger;' keyword exists? - Stack Overflow

programmeradmin3浏览0评论

Sometimes some developers forgot to remove debugger; in javascript code, and it produce javascript error on IE. How can you check (like for the console: if(window.console){console.log('foo');}) if a debugger exists?

BTW: I don't want to detect if the browser is IE, I want a generic method if possible Thanks,

Sometimes some developers forgot to remove debugger; in javascript code, and it produce javascript error on IE. How can you check (like for the console: if(window.console){console.log('foo');}) if a debugger exists?

BTW: I don't want to detect if the browser is IE, I want a generic method if possible Thanks,

Share Improve this question asked Mar 24, 2011 at 10:57 JohnJohnGaJohnJohnGa 15.7k20 gold badges64 silver badges87 bronze badges
Add a comment  | 

4 Answers 4

Reset to default 13

You cannot.

The best solution would be adding a hook to your version control system to prevent code containing debugger; statements from being committed/pushed.

Asking your devs to search for debugger; or at least have a careful look at the diff before committing is also a solution - but not as effective as hard-rejecting in the VCS.

You could attempt to compile a function that declares debugger as a local variable. If debugger is reserved as a keyword, the JS engine will throw an error which you can catch.

var debuggerIsKeyword = false;
try {
    new Function("var debugger;");
} catch(e) {
    debuggerIsKeyword = true;
}

However I'm not sure that knowing whether a keyword exists or not is actually helpful.

Maybe the safest approach is to have a global include file for all your projects that stubs out the debugger if it doesn't exist:

if (typeof debugger == 'undefined') {
    window.debugger = null;
}

That way calls to debugger just become a reference to null. which is harmless. Seems like a better approach than expecting forgetful developers to wrap each debugger call in an if statement.

The same approach works for console.log, etc.

EDIT: As AndrewF points out, debugger is actually a keyword, not a global, so this won't work. The same effect can be achieved using the following without throwing an error:

window['debugger'] = null;

Haven't tried it for lack of an IE, but this should work:

if (typeof console !== 'undefined') {
  console.log("logging enabled");    
}
发布评论

评论列表(0)

  1. 暂无评论