Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

EnvironmentDetection

uupaa edited this pageMay 19, 2017 ·30 revisions

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

BrowserESModulesWorkerNode.jsNW.jsElectron
render
Electron
main
typeof thisobject---objectobject-
typeof windowobjectobject--objectobject-
typeof selfobjectobjectobject-objectobject-
typeof global---objectobjectobjectobject
typeof GLOBAL---object-objectobject
typeof documentobjectobject--objectobject-
typeof WorkerLocation--object----
typeof __dirname---string-stringstring
typeof __filename---string-stringstring
setTimeout + ""nativenativenative!nativenativenative!native
process.type-----"renderer""browser"

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

varGLOBAL=(this||0).self||(typeofself!=="undefined") ?self :global;// --- environment detection -------------------------------// https://github.com/uupaa/WebModule/wiki/EnvironmentDetection(function(){varhasGlobal=!!GLOBAL.global;// Node.js, NW.js, ElectronvarprocessType=!!(GLOBAL.process||0).type;// Electron(render and main)varnativeTimer=!!/native/.test(setTimeout);// Node.js, Electron(main)GLOBAL.IN_BROWSER=!hasGlobal&&"document"inGLOBAL;// Browser and WorkerGLOBAL.IN_WORKER=!hasGlobal&&"WorkerLocation"inGLOBAL;// WorkerGLOBAL.IN_NODE=hasGlobal&&!processType&&!nativeTimer;// Node.jsGLOBAL.IN_NW=hasGlobal&&!processType&&nativeTimer;// NW.jsGLOBAL.IN_EL=hasGlobal&&processType;// Electron(render and main)})();
  • ブラウザ(Browser, Worker) でIN_BROWSER が true になります
  • Worker でIN_WORKER が true になります
  • Node.js でIN_NODE が true になります
  • NW.js でIN_NW が true になります
  • Electron でIN_EL が true になります

IN_xxx はグローバル変数として export されます。これらを参照することで、それぞれの環境に適したコードを簡単に記述できます。

if(IN_EL||IN_NW){    ...}elseif(IN_BROWSER){    ...}
Clone this wiki locally

[8]ページ先頭

©2009-2025 Movatter.jp