简体   繁体   English

javascript获取执行环境

[英]javascript getting the execution environment

I need to get the execution environment of JS code. 我需要获取JS代码的执行环境。 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. 如果代码不是从Firebug等控制台运行的,我想添加一些功能,并在从控制台环境运行该代码时将其禁用。

You can use this simple function: 您可以使用以下简单功能:

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

It will return true if script is running in window namespace (browser). 如果脚本在窗口名称空间(浏览器)中运行,它将返回true。

Here is jsfiddle 这是jsfiddle

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 这是JS Bin

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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