Skip to content

EnvironmentDetection

uupaa edited this page Mar 26, 2016 · 30 revisions

WebModule が直接的にサポートしている環境における特徴点を洗い出したものが以下の表になります。

typeof * Browser Worker Node NW.js Electron
render
Electron
main
window object - - object object -
self object object - object object -
global - - object object object object
GLOBAL - - object - object object
document object - - object object -
WorkerLocation - object - - - -
__dirname - - string - string string
__filename - - string - string string
setTimeout + "" native native custom native native custom
process.type - - - - renderer browser

このパズルを解き、コンパクトにまとめたものが、WebModule.js の冒頭にある、環境判別処理になります。

var GLOBAL = (this || 0).self || global;

// --- environment detection -------------------------------
// https://github.com/uupaa/WebModule/wiki/EnvironmentDetection
(function() {

var hasGlobal     = !!GLOBAL.global;              // Node.js, NW.js, Electron
var processType   = !!(GLOBAL.process || 0).type; // Electron(render and main)
var nativeTimer   = !!/native/.test(setTimeout);  // Node.js, Electron(main)

GLOBAL.IN_BROWSER = !hasGlobal && "document"       in GLOBAL;
GLOBAL.IN_WORKER  = !hasGlobal && "WorkerLocation" in GLOBAL;
GLOBAL.IN_NODE    =  hasGlobal && !processType && !nativeTimer;
GLOBAL.IN_NW      =  hasGlobal && !processType &&  nativeTimer;
GLOBAL.IN_EL      =  hasGlobal &&  processType;

})();
  • ブラウザ環境(Browser, Worker) で IN_BROWSER が true になります
  • Worker で IN_WORKER が true になります
  • Node.js で IN_NODE が true になります
  • NW.js で IN_NW が true になります
  • Electron で IN_EL が true になります

Clone this wiki locally