Last active
April 15, 2021 10:50
-
-
Save marcop135/0f93ecaf69abd2d2d327de486c10fd88 to your computer and use it in GitHub Desktop.
Find global object available in any JS environments (web browsers, Node.js, web workers, etc.) — or use globalThis
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!doctype html> | |
<html> | |
<head> | |
<title>What's the global object available?</title> | |
<script> | |
var getGlobal = function () { | |
if (typeof window !== 'undefined') { | |
return window; // Client-side JavaScript | |
} | |
if (typeof self !== 'undefined') { | |
return self; // Client-side JavaScript / Web workers | |
} | |
if (typeof global !== 'undefined') { | |
return global; // Node.js | |
} | |
}; | |
var __global__ = getGlobal(); | |
if (typeof __global__.alert === 'function') { | |
console.log('Client-side land!'); | |
} else { | |
console.log('Node.js land!'); | |
}; | |
</script> | |
</head> | |
<body> | |
<pre><code>var getGlobal = function () { | |
if (typeof window !== 'undefined') { | |
return window; // Client-side JavaScript | |
} | |
if (typeof self !== 'undefined') { | |
return self; // Client-side JavaScript / Web workers | |
} | |
if (typeof global !== 'undefined') { | |
return global; // Node.js | |
} | |
}; | |
var __global__ = getGlobal(); | |
if (typeof __global__.alert === 'function') { | |
console.log('Client-side land!'); | |
} else { | |
console.log('Node.js land!'); | |
}; | |
</code></pre> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment