Skip to content

Instantly share code, notes, and snippets.

@marcop135
Last active April 15, 2021 10:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save marcop135/0f93ecaf69abd2d2d327de486c10fd88 to your computer and use it in GitHub Desktop.
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
<!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