-
Notifications
You must be signed in to change notification settings - Fork 8
EnvironmentDetection
uupaa edited this page Mar 26, 2016
·
30 revisions
それぞれの環境における特徴点を洗い出したものが以下になります。
| 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;
})();