From 37d3fb78d3ae791b10300205f9d7fe184f4a05e0 Mon Sep 17 00:00:00 2001 From: "Michael Bradley, Jr" Date: Thu, 15 Aug 2019 13:32:52 -0500 Subject: [PATCH] Use es5-ext/global as a more robust way to resolve browser's window The [es5-ext/global][es5g] module is based on Mathias Bynens' [polyfill][poly] for [`globalThis`][gT]. It uses the same robust technique but is more conservative in that it does not add a `globalThis` property to the resolved object, i.e. `window` in a browser and `global` in Node. It also lacks the "old IE" fallback seen in a [demo][demo] of the original polyfill, but that is easily provided in this commit. [es5g]: https://github.com/medikoo/es5-ext/blob/master/global.js [poly]: https://mathiasbynens.be/notes/globalthis [gT]: https://github.com/tc39/proposal-global [demo]: https://mathiasbynens.be/demo/globalthis-ie --- lib/browser.js | 17 ++++++++++------- package.json | 1 + 2 files changed, 11 insertions(+), 7 deletions(-) diff --git a/lib/browser.js b/lib/browser.js index 51d19792..e536702e 100644 --- a/lib/browser.js +++ b/lib/browser.js @@ -1,10 +1,13 @@ -var _global = (function () { - if (!this && typeof global !== 'undefined') { - return global; - } - return this; -})(); -var NativeWebSocket = _global.WebSocket || _global.MozWebSocket; +var _globalThis; +try { + _globalThis = require('es5-ext/global'); +} catch (error) { +} finally { + if (!_globalThis && typeof window !== 'undefined') { _globalThis = window; } + if (!_globalThis) { throw new Error('Could not determine global this'); } +} + +var NativeWebSocket = _globalThis.WebSocket || _globalThis.MozWebSocket; var websocket_version = require('./version'); diff --git a/package.json b/package.json index 7aeb5cec..4cbff181 100644 --- a/package.json +++ b/package.json @@ -28,6 +28,7 @@ }, "dependencies": { "debug": "^2.2.0", + "es5-ext": "^0.10.50", "nan": "^2.14.0", "typedarray-to-buffer": "^3.1.5", "yaeti": "^0.0.6"