Skip to content

fix: use a static object as fallback of the global object #1901

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Feb 19, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 9 additions & 1 deletion packages/utils/src/misc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,14 +20,22 @@ export function isNodeEnv(): boolean {
return Object.prototype.toString.call(typeof process !== 'undefined' ? process : 0) === '[object process]';
}

const fallbackGlobalObject = {};

/**
* Safely get global scope object
*
* @returns Global scope object
*/
// tslint:disable:strict-type-predicates
export function getGlobalObject(): Window | NodeJS.Global | {} {
return isNodeEnv() ? global : typeof window !== 'undefined' ? window : typeof self !== 'undefined' ? self : {};
return isNodeEnv()
? global
: typeof window !== 'undefined'
? window
: typeof self !== 'undefined'
? self
: fallbackGlobalObject;
}
// tslint:enable:strict-type-predicates

Expand Down
13 changes: 12 additions & 1 deletion packages/utils/test/misc.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { getEventDescription } from '../src/misc';
import { getEventDescription, getGlobalObject } from '../src/misc';

describe('getEventDescription()', () => {
test('message event', () => {
Expand Down Expand Up @@ -108,3 +108,14 @@ describe('getEventDescription()', () => {
).toEqual('<unknown>');
});
});

describe('getGlobalObject()', () => {
test('should return the same object', () => {
const backup = global.process;
delete global.process;
const first = getGlobalObject();
const second = getGlobalObject();
expect(first).toEqual(second);
global.process = backup;
});
});