简体   繁体   中英

Execute JS code only in debug mode

Is it posible to execute part of a js file only when I have the developer tools opened?

I want something like

#if DEBUG
executeMethodOnlyInDebugger();
#endif

but for JavaScript.

不,javascript 本身没有条件编译

Not really. But you can use devtools-detect for that. See the following answer: enter link description here

Try this library: https://github.com/sindresorhus/devtools-detect

It does some inspection of the window object and emits an event when it detects the console has opened. I would probably be wary of including this in production code but it could make for a useful debugging tool in your use case.

I dont think there is a way to check for that in Chrome and Firefox. The best bet is to have a debug flag in your code.

Although IE gives console as undefined when developer tool is not open. So for IE you can just do:

if(console){
  //dev tools is open
} else{
  //dev tools not open
}

Also have a look here for more info on chrome: Find out whether Chrome console is open

For ASP.NET

In _Layout.cshtml (for MVC) or Master (for web forms), add the following:

<script>
    @if (HttpContext.Current.IsDebuggingEnabled)
    {
    @:var DEBUG = true;
    }
    else
    {
    @:var DEBUG = false;
    }
    alert('DEBUG: ' + DEBUG);
</script>

The beauty of this is that you can turn it on/off using a configuration value in Web.config to allow debugging in any environment:

<system.web>
    <compilation debug="false" />
</system.web>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM