Skip to content
Merged
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
24 changes: 16 additions & 8 deletions index.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,12 @@
const ONESIGNAL_SDK_ID = 'onesignal-sdk';
const ONE_SIGNAL_SCRIPT_SRC =
const DEFAULT_SCRIPT_SRC =
'https://cdn.onesignal.com/sdks/web/v16/OneSignalSDK.page.js';

// true if the script is successfully loaded from CDN.
let isOneSignalInitialized = false;
// true if the script fails to load from CDN. A separate flag is necessary
// to disambiguate between a CDN load failure and a delayed call to
// OneSignal#init.
let isOneSignalScriptFailed = false;

if (typeof window !== 'undefined') {
window.OneSignalDeferred = window.OneSignalDeferred || [];
addSDKScript();
}

declare global {
Expand All @@ -30,11 +25,15 @@ function handleOnError() {
isOneSignalScriptFailed = true;
}

function addSDKScript() {
function addSDKScript(scriptSrc?: string) {
if (document.getElementById(ONESIGNAL_SDK_ID)) {
return;
}

const script = document.createElement('script');
script.id = ONESIGNAL_SDK_ID;
script.defer = true;
script.src = ONE_SIGNAL_SCRIPT_SRC;
script.src = scriptSrc || DEFAULT_SCRIPT_SRC;

// Always resolve whether or not the script is successfully initialized.
// This is important for users who may block cdn.onesignal.com w/ adblock.
Expand Down Expand Up @@ -112,6 +111,8 @@ const init = (options: IInitObject): Promise<void> => {
options.welcomeNotification.disable = options.welcomeNotification.disabled;
}

addSDKScript(options.scriptSrc);

return new Promise<void>((resolve, reject) => {
window.OneSignalDeferred?.push((OneSignal) => {
OneSignal.init(options)
Expand Down Expand Up @@ -457,6 +458,13 @@ export interface IInitObject {
serviceWorkerParam?: { scope: string };
serviceWorkerPath?: string;
serviceWorkerOverrideForTypical?: boolean;
/**
* Overrides the default OneSignal SDK script URL.
* Use this to self-host the SDK script on your own domain, e.g. to comply
* with strict Cross-Origin-Embedder-Policy (COEP) or Content-Security-Policy (CSP) headers.
* @default 'https://cdn.onesignal.com/sdks/web/v16/OneSignalSDK.page.js'
*/
scriptSrc?: string;
[key: string]: unknown;
}

Expand Down