diff --git a/src/navspa.tsx b/src/navspa.tsx index 0c62b7f..b1e17ca 100644 --- a/src/navspa.tsx +++ b/src/navspa.tsx @@ -1,7 +1,7 @@ import * as React from 'react'; import * as ReactDOM from 'react-dom'; import * as Feilmelding from './feilmelding'; -import { createCustomEvent } from './utils'; +import { createCustomEvent, getGlobal } from './utils'; interface DeprecatedNAVSPAScope { [name: string]: DeprecatedNAVSPAApp; @@ -23,8 +23,9 @@ type NAVSPAApp = { unmount(element: HTMLElement): void; } -export const scope: DeprecatedNAVSPAScope = (global as any)['NAVSPA'] = (global as any)['NAVSPA'] || {}; // tslint:disable-line -export const scopeV2: NAVSPAScope = (global as any)['NAVSPA-V2'] = (global as any)['NAVSPA-V2'] || {}; // tslint:disable-line +const globalScope = getGlobal(); +export const scope: DeprecatedNAVSPAScope = globalScope['NAVSPA'] = globalScope['NAVSPA'] || {}; +export const scopeV2: NAVSPAScope = globalScope['NAVSPA-V2'] = globalScope['NAVSPA-V2'] || {}; export const exportEvent: string = 'NAVSPA-eksporter'; export function eksporter(name: string, component: React.ComponentType) { diff --git a/src/utils.ts b/src/utils.ts index f934d8d..c382264 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -1,3 +1,4 @@ +/* istanbul ignore file */ export function createCustomEvent(type: string, detail: T): Event { try { return new CustomEvent(type, { detail }); @@ -7,4 +8,15 @@ export function createCustomEvent(type: string, detail: T): Event { event.initCustomEvent(type, false, false, detail); return event; } +} + +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/globalThis +export function getGlobal(): { 'NAVSPA': {}, 'NAVSPA-V2': {} } { + if (typeof globalThis !== 'undefined') return globalThis as any; + + // IE11 fallback + if (typeof self !== 'undefined') return self as any; + if (typeof window !== 'undefined') return window as any; + if (typeof global !== 'undefined') return global as any; + throw new Error('Unable to locate globale object'); } \ No newline at end of file