在javascript中检测的“Window”部分,
在javascript中检测[object Window]的“Window”部分和/或判断代码是否在节点服务器或浏览器上运行
垃圾更多的上下文。 我正在为应用程序在客户端和服务器上运行的nodejs编写一个模块。 我需要在几个地方有所不同,所以我需要检测它在哪里运行。 现在我将“this”传递给init函数,该函数在服务器上给我[对象对象]和浏览器中的[对象窗口]。 …但我不知道如何检查窗口/对象部分。 typeof似乎检查领先的“对象”部分。 思考? 提前致谢
如果您确定会在node.js和浏览器中的[object Window]
中收到[object Object]
,那么只需检查
var isBrowser = (this.toString().indexOf('Window') != -1); var isServer = !isBrowser;
一个string的indexOf
方法检查它在该string中的参数的位置。 返回值-1
表示参数不作为子string存在。
更新
正如其他人build议检查window
对象的存在,您可以等效地检查您期望在浏览器中存在的其他对象,如navigator
器或location
。 但是,这种检查,上面已经提出:
var isBrowser = (this.window == this);
最终会在node.js中引用一个参考错误 正确的做法是
var isBrowser = ('window' in this);
或者,正如我所说的
var isBrowser = ('navigator' in this); var isBrowser = ('location' in this);
[object Window]
不可靠。 一些较旧的浏览器只是说[object]
或[object Object]
而不考虑[object Object]
的types。
试试这个:
var isBrowser = this instanceof Window;
或者,因为我从来没有使用Node.js,那么这个怎么样?
var isBrowser = typeof Window != "undefined";
如果你只是想知道你是否在Node上运行,看看this === this.window
。
if (this === this.window) { // Browser } else { // Node }
这比希望toString
更加可靠,实现是一致的,事实并非如此。
为了简单起见,我不认为你可以击败:
if('window' in this) { // It's a browser }
基本上,您正在问如何检测脚本= x中的Node.js
下面是从Underscore.js中修改和扩展的,我也为我的一些客户/服务器模块代码使用了一个varient。 它基本上扫描了对node.js有点独特的全局variables(除非你在客户端= x中创build它们)
这是为了提供一个替代的答案,以防万一它是所需要的。
(function() { //this is runned globally at the top somewhere //Scans the global variable space for variables unique to node.js if(typeof module !== 'undefined' && module.exports && typeof require !== 'undefined' && require.resolve ) { this.isNodeJs = true; } else { this.isNodeJs = false; } })();
或者,如果您只想在需要时调用它
function isNodeJs() { //this is placed globally at the top somewhere //Scans the global variable space for variables unique to node.js if(typeof module !== 'undefined' && module.exports && typeof require !== 'undefined' && require.resolve ) { return true; } else { return false; } };