1

I need to get the execution environment of JS code. if it is a console or if it browser. How should I approach this?

for instance:

if(exec_type() == 'browser')
{
 // do something
}

What is the purpose of it? I want to add some functionality if the code is not run from a console such as firebug, and to disable them when it is run from console environment.

  • 1
    This might be relevant, and might lead you to what you're looking for: http://stackoverflow.com/questions/21692646/how-does-facebook-disable-the-browsers-integrated-developer-tools/21692733#21692733 – Colin DeClue Feb 25 '14 at 19:03
  • There's no easy, x-way of doing this. If you could list the specific consoles you're targeting, it might be possible to give you parameters to check for, to see if you're in *that specific environment*. – Matt Feb 25 '14 at 19:03
  • you would have to use quirky method to do it this way, ex: (function(){ return arguments.callee.caller }()), you'de be better off passing a flag to your code. – dandavis Feb 25 '14 at 19:04
  • What is "*a console*"??? The node.js prompt? – Bergi Feb 25 '14 at 19:53
  • Can you please re-word this? You use the term `console` too much for this to make sense. – Jasper Feb 25 '14 at 22:33

2 Answers2

0

You can use this simple function:

function isInWindow() {
  return this === window;
}

It will return true if script is running in window namespace (browser).

Here is jsfiddle

c-smile
  • 26,734
  • 7
  • 59
  • 86
  • If I run this code in a JS console it returns `true`. What does this help you identify exactly? For instance, where will this function return `false`? – Jasper Feb 25 '14 at 21:55
  • 1
    @Jasper If you run this in console attached to the window it will return you `true`. If you will run this under, say, node.js it will return you `false`. – c-smile Feb 25 '14 at 22:28
0

Maybe these functions will help you.

function isInWindow(){
  if(typeof window === "object"){
    return true;  
  }else{
    return false;
  }
}
function isInNode(){
  if(typeof global === "object"){
    return true;  
  }else{
    return false;
  }
}
console.log(isInWindow); // true, if in browser
console.log(isInNode);  // true, if in node.js

Here is JS Bin

soarinblue
  • 1,517
  • 3
  • 21
  • 30