Web SDK

OneSignal frontend website SDK.

These methods serve as a reference and are just a single step in the setup process. Make sure to follow the steps for your particular platform here:

Setup

You may notice the need to wrap your OneSignal calls with OneSignalDeferred.push(function() { ... })

You can add as many methods into the function() as desired.

The OneSignal SDK is loaded with the defer attribute on your page. For example:

<script src="https://cdn.onesignal.com/sdks/web/v16/OneSignalSDK.page.js" defer></script>

This means the OneSignal code will execute after the HTML document has been fully parsed, preventing any blocking of the site by the OneSignal SDK. However, this presents a problem for page scripts that depend on the OneSignalDeferred variable existing. To resolve this, when you add OneSignal to your site, it should begin with:

window.OneSignalDeferred = window.OneSignalDeferred || [];

This creates a OneSignalDeferred variable, and if OneSignal is already loaded, it's then assigned to the loaded instance. Otherwise, the OneSignal variable equals an empty array - [].

All arrays have a .push() function, so at this point, the OneSignalDeferred variable is simply an array of functions we're pushing on to it. When the SDK finally loads, the SDK processes all the functions pushed so far and redefines .push().

Initialize the SDK

This should be called only once during application startup.

Call this from each page of your site to initialize OneSignal. This call is required before any other functions can be used.

OneSignal.init({
	appId: "YOUR ONESIGNAL APP ID"
});
// init(config: AppUserConfig): Promise<void>
OneSignal.init({
	appId: "YOUR ONESIGNAL APP ID"
});

Init options are as follows. These only work with Custom Code Setup:

ParameterTypeDescription
appIdStringRequired: Your OneSignal app id found on the settings page at onesignal.com.
requiresUserPrivacyConsentBooleanAllows you to delay the initialization of the SDK until the user provides privacy consent. The SDK will not be fully initialized until the provideUserConsent function is called.
safari_web_idStringThe bundle ID for your Safari p12 certificate uploaded to the OneSignal dashboard. See Web Quickstart.
promptOptionsJSONLocalize the popup prompts. See below details.
welcomeNotificationJSONCustomize or disable the welcome notification sent to new site subscribers. See below details.
notifyButtonJSONEnable and customize the notifyButton. See below details.
persistNotificationBooleanChrome (non-mobile) - true: persists notification, false: disappears after some time. See our Notification Persistence Section for more info.

Firefox and Safari - notifications automatically dismiss after some time and this parameter does not control that.
webhooksJSONSee our Webhooks page for the nested options.
autoResubscribeBooleanRecommended, HTTPS ONLY - Automatically resubscribes users when they clear browser cache or migrating to OneSignal.

This is set in the OneSignal dashboard during setup but if set again during initialization, will override dashboard config.
notificationClickHandlerMatchStringDefault: If the launch URL of the notification matches exactly to a tab already open it will be focused.

"origin"- If the launch URL of the notification matches any tab already open to your domain it will be focused.
See Listening to events on the notification documentation for more details.
notificationClickHandlerActionString"navigate" Default: Automatically navigate to the launchURL on opening the notification.

"focus" - Only apply if notificationClickHandlerMatch is set to "origin". Only focuses an existing tab if the launch URL matches the domain instead of navigating.
See Listening to events on the notification documentation for more details.
pathStringSpecial Case on HTTPS ONLY: Absolute path to OneSignal SDK web worker files. You only need to set this parameter if you do not want the files at the root of your site.

Init promptOptions parameters

Pass in these optional parameters within promptOptions when initializing to localize the prompts to your custom text and language. All entries are limited in length. Foreign characters accepted. Each parameter is optional, and its default is used when it is not included.

ParameterTypeDescription
slidedownJSONThis object contains an array of prompts with the below options.
promptsArray of ObjectsSetup multiple prompt types, each as their own object in the prompts array.

Example:
"slidedown": { "prompts": [{...}, {...}, {...}] }
typeStringPush Prompt Types:
- push which is the Slide Prompt without categories.
- category which is the Category Prompt. Acts like the Slide Prompt but includes up to 10 categories (tags) a user can select upon opt-in.

Email and SMS Types:
- sms only asks for phone number.
- email only asks for email address.
- smsAndEmail asks for both.
See Email & Phone Number Web Prompt for details.
autoPromptBooleantrue will display the prompt based on the delay options.
false will prevent the prompt from displaying until the Slidedowns methods are used.
textJSONAll Slidedown Text
- actionMessage: The callout asking the user to opt-in. Up to 90 characters.
- acceptButton: Triggers the opt-in. Up to 15 characters.
- cancelButton: Cancels opt-in. Up to 15 characters.

Category Prompt Specific Text
- negativeUpdateButton: Cancels the category update. Up to 15 characters.
- positiveUpdateButton: Saves the updated category tags. Up to 15 characters.
- updateMessage: A different message shown to subscribers presented the prompt again to update categories. Up to 90 characters.

Email & Phone Prompt Specific Text
- emailLabel: Identifies the email text field. Up to 15 characters.
- smsLabel: Identifies the phone number text field. Up to 15 characters.
- updateMessage: A different message shown to subscribers presented the prompt again to update email and/or phone number. Up to 90 characters.
- negativeUpdateButton: Cancels the update. Up to 15 characters.
- positiveUpdateButton: Saves the new phone number and/or email address. Up to 15 characters.
- confirmMessage: The message of the confirmation prompt displayed after the email and/or phone number is provided. Up to 90 characters.
delayJSON- pageViews: The number of pages a user needs to visit before the prompt is displayed.
- timeDelay: The number of seconds a user needs to wait before the prompt is displayed.

Both options must be satisfied for the prompt to display. Example:
delay: { pageViews: 3, timeDelay: 20 }
The user will not be shown the prompt until 20 seconds after the 3rd page view.
categoriesArray of ObjectsOnly available for type: category.
Up to 10 categories consisting of a tag which is the key (See Data Tags) and label which is what the user sees within the prompt. For example:
categories: [ {tag: "local_news", label: "Local News"}, { tag: "world_news", label: "World News"} ]
The user will be tagged with local_news but will see "Local News" in the prompt.
See Category Prompt for details.

Init welcomeNotification parameters

Pass in these optional parameters within welcomeNotification when initializing to customize or disable the welcome notification sent to new site visitors. Any person visiting your site for their first time, or an existing user who has completely cleared their cache is considered a new site visitor.

ParameterTypeDescription
disableBooleanDisables sending a welcome notification to new site visitors. If you want to disable welcome notifications, this is the only option you need.
titleStringThe welcome notification's title. You can localize this to your own language. If not set, or left blank, the site's title will be used. Set to one space ' ' to clear the title, although this is not recommended.
messageStringRequired: The welcome notification's message. You can localize this to your own language. A message is required. If left blank or set to blank, the default of 'Thanks for subscribing!' will be used.
urlURLAn optional URL to open after the user clicks the welcome notification.

By default, clicking the welcome notification does not open any link. This is recommended because the user has just visited your site and subscribed.

Init notifyButton parameters

Pass in these optional parameters within notifyButton when initializing to enable and customize the Subscription Bell (formerly known as the notify button). All parameters below are optional. If not set, they will be replaced with their defaults.

ParameterTypeDescription
enableBooleanEnable the Subscription Bell. The Subscription Bell is otherwise disabled by default.
displayPredicateFunctionA function you define that returns true to show the Subscription Bell, or false to hide it. You can also return a Promise that resolves to true or false for awaiting asynchronous operations.

Typically used the hide the Subscription Bell after the user is subscribed.

This function is not re-evaluated on every state change; this function is only evaluated once when the Subscription Bell begins to show.
sizeStringOne of 'small', 'medium', or 'large'. The Subscription Bell will initially appear at one of these sizes, and then shrink down to size 'small' after the user subscribes.
positionStringEither 'bottom-left' or 'bottom-right'. The Subscription Bell will be fixed at this location on your page.
offsetJSONSpecify CSS-valid pixel offsets using bottom, left, and right.
prenotifyBooleanIf true, the Subscription Bell will display an icon that there is 1 unread message. When hovering over the Subscription Bell, the user will see custom text set by message.prenotify.
showCreditBooleanSet false to hide the 'Powered by OneSignal' text in the Subscription Bell dialog popup.
textJSONCustomize the Subscription Bell text. See the example code below to know what to change.

The following is a basic template of how you would call init().

<script src="https://cdn.onesignal.com/sdks/web/v16/OneSignalSDK.page.js" defer></script>
<script>
window.OneSignalDeferred = window.OneSignalDeferred || [];
OneSignalDeferred.push(function(OneSignal) {
  OneSignal.init({
    appId: "99397374-10fe-4865-b62d-d8b71114b320",
    safari_web_id: "web.onesignal.auto.20f3ee95-6f21-4aad-a9bb-9c5899a4353a",
    notifyButton: {
      enable: true,
    },
    promptOptions: {
      slidedown: {
        prompts: [{
            type: "smsAndEmail",
            autoPrompt: false,
            text: {
              emailLabel: "Insert Email Address",
              smsLabel: "Insert Phone Number",
              acceptButton: "Submit",
              cancelButton: "No Thanks",
              actionMessage: "Receive the latest news, updates and offers as they happen.",
              updateMessage: "Update your push notification subscription preferences.",
              confirmMessage: "Thank You!",
              positiveUpdateButton: "Save Preferences",
              negativeUpdateButton: "Cancel",
            },
            delay: {
              pageViews: 1,
              timeDelay: 20
            },
          },
          {
            type: "category",
            autoPrompt: true,
            text: {
              actionMessage: "We'd like to show you notifications for the latest news and updates.",
              acceptButton: "Allow",
              cancelButton: "Cancel",

              /* CATEGORY SLIDEDOWN SPECIFIC TEXT */
              negativeUpdateButton: "Cancel",
              positiveUpdateButton: "Save Preferences",
              updateMessage: "Update your push notification subscription preferences.",
            },
            delay: {
              pageViews: 3,
              timeDelay: 20
            },
            categories: [{
                tag: "politics",
                label: "Politics"
              },
              {
                tag: "local_news",
                label: "Local News"
              },
              {
                tag: "world_news",
                label: "World News",
              },
              {
                tag: "culture",
                label: "Culture"
              },
            ]
          }
        ]
      }
    }
  });
});
</script>

User

When your users subscribe to push notifications on your website, OneSignal creates a User record (onesignal_id) and Subscription record (subscription_id). Users can have multiple subscription records which you identify as belonging to a specific user through the use of the login method which sets the external_id.

Log in a user (Set an External ID)

The login method identifies a user by setting the external_id alias. Logging in a user with the OneSignal SDK will switch the context to that specific user.

  • If the external_id exists, the user will be retrieved, and the context will be set from that user information. If operations have already been performed under a device-scoped user, they will not be applied to the now logged-in user, and their information will be lost.
  • If the external_id does not exist, the user will be created, and the context will be set from the current local state. If operations have already been performed under a device-scoped user, those operations will be applied to the newly created user.

📘

External ID / Aliases

external_id and other aliases can only be set for a subscription that has initially allowed notifications, and has a record in the OneSignal dashboard.

It's best to wrap the login method within our pushSubscriptionChangeListener which triggers when the subscription record status changes.

OneSignalDeferred.push(function() {
  OneSignal.login("EID");
});

Log out a user (Remove an External ID)

Log out the user previously logged in via login. The user property now references a new device-scoped user. A device-scoped user has no user identity that can later be retrieved, except through this device, as long as the app remains installed and the app data is not cleared.

OneSignalDeferred.push(function() {
  OneSignal.logout();
});

Add an alias

Set an alias for the current user. If the alias label exists on this user, it will be overwritten.

OneSignalDeferred.push(function() {
  OneSignal.User.addAlias("ALIAS_LABEL", "ALIAS_ID");
});

Add multiple aliases

Set aliases for the current user. If any alias labels exist on the user, they will be overwritten.

const aliases = {
 ALIAS_LABEL_01: "ALIAS_ID_01",
 ALIAS_LABEL_02: "ALIAS_ID_02",
 ALIAS_LABEL_03: "ALIAS_ID_03", 
};

OneSignalDeferred.push(function() {
  OneSignal.User.addAliases(["ALIAS_LABEL_01": "ALIAS_ID_01", "ALIAS_LABEL_02": "ALIAS_ID_02"]);
});

Remove an alias

Remove an alias from the current user.

OneSignalDeferred.push(function() {
  OneSignal.User.removeAlias("ALIAS_LABEL");
});

Remove multiple aliases

Remove aliases from the current user.

const aliases = ["ALIAS_LABEL_01", "ALIAS_LABEL_02", "ALIAS_LABEL_03"];

OneSignalDeferred.push(function() {
  OneSignal.User.removeAliases(aliases);
});


Data Tags

Data Tags are custom key : value pairs of string or number data you set on users based on events or user data of your choosing. See Data Tags Overview for more details on what tags are used for.

See Data Tag Implementation for SDK Method details.


Privacy

Require privacy consent

Determines whether users must consent to privacy before sending their data to OneSignal. This should be set to true to ensure compliance before invoking the init method.

OneSignalDeferred.push(function() {
  OneSignal.setConsentRequired(true);
});

Provide user consent

Sets whether privacy consent has been granted.

If your website is set to require the user's privacy consent or some action before they can subscribe to push, add requiresUserPrivacyConsent: true property in the OneSignal init call. This will stop our SDK from initializing until you call provideUserConsent(true).

You can also revoke consent by setting provideUserConsent(false). This will prevent further collection of user data. To delete the user's current data see Delete User Data.

OneSignalDeferred.push(function() {
  OneSignal.setConsentGiven(true);
});


Push Notifications

Set a default launch URL

Sets the default URL for notifications.

If you haven't set a default URL, your notification will open to the root of your site by default.

OneSignalDeferred.push(function() {
  OneSignal.Notifications.setDefaultUrl("https://onesignal.com");
});

To set the default URL for notifications, provide a valid URL that you want to be launched when the notification is clicked. This default URL will be used if no other URL is specified when creating a notification. If you do specify a URL when creating a notification, the default URL will be overridden.

In the case of Safari, the default notification icon URL will be set to the Site URL that you have specified in your Safari settings, as this function is not available.

Set a default title

Sets the default title to display on notifications.

OneSignalDeferred.push(function() {
  OneSignal.Notifications.setDefaultTitle("Powered by OneSignal!");
});

If a notification is created with a title, the specified title always overrides this default title.

A notification's title defaults to the title of the page the user last visited. If your page titles vary between pages, this inconsistency can be undesirable. Call this to standardize page titles across notifications, as long as a notification title isn't specified.

Check for push support

Returns true if the current browser supports web push.

OneSignalDeferred.push(function() {
  const isSupported = OneSignal.Notifications.isPushSupported();
});

Get notification permission status

Determine whether your site has notification permission.

This returns true when your site has permission to display notifications.

  • This is just the sites's permission, does not factor in OneSignal's optOut status or the existence of the Subscription ID and Push Token, see OneSignal.User.PushSubscription for these.
OneSignalDeferred.push(function() {
  let permission = await OneSignal.Notifications.permission; // boolean
});

If you're deleting your user entry on our online dashboard for testing, the SDK will not sync with our dashboard and so this method will still return true (because the browser itself remembers the site's permissions). Follow Clearing your cache and resetting push permissions to reset this in the browser itself.

Request notification permission

Requests push notifications permission via the native browser prompt.

Web SDK v15 see showNativePrompt method.

OneSignalDeferred.push(function() {
  OneSignal.Notifications.requestPermission();
});

Listen to events on the notification

You can hook into the notification life-cycle by attaching your event handlers to a notification event. Calling addEventListener lets you add an arbitrary number of event handlers for notification events.

function eventListener(event) {
  console.log(`${event}`);
}

OneSignalDeferred.push(function() {
  OneSignal.Notifications.addEventListener("eventname", eventListener);
});

Notification Events

Event NameDescription
clickOccurs when the user taps or clicks on the notification.
dismissOccurs when a notification is dismissed, such as swiping it away or clicking close on the notification.
permissionChangeOccurs whenever a user changes their notification permission setting.
permissionPromptDisplayOccurs when the native notification permission prompt is shown.
foregroundWillDisplayOccurs just before the notification is presented to the user.

Remove event handlers

Removes the event handler for the given event.

function eventListener(event) { // ... }

OneSignalDeferred.push(function() {
  OneSignal.Notifications.removeEventListener("eventname", eventListener);
});

Notification clicked

This event will fire when the notification's body/title or action buttons are clicked.

ParameterTypeDescription
notificationNotificationAn object describing the notification that was clicked.
resultNotificationClickResultAn object containing the actionId of the click and the launch url of the click.
function clickEventListener(event) {
  console.log(`click event: ${event}`);
}

OneSignalDeferred.push(function() {
  OneSignal.Notifications.addEventListener("click", clickEventListener);
});

Notification will display

This event is called prior to a notification being displayed. This event is fired on your page. If multiple browser tabs are open to your site, this event will be fired on all pages on which OneSignal is active.

ParameterTypeDescription
notificationNotificationThe notification that will display.
function foregroundWillDisplayListener(event) {
  console.log(`notification will display: ${notification}`);
}

OneSignalDeferred.push(function() {
  OneSignal.Notifications.addEventListener("foregroundWillDisplay", foregroundWillDisplayListener);
});

Notification dismissed

This event occurs when:

  • A user purposely dismisses the notification without clicking the notification body or action buttons
  • On Chrome on Android, a user dismisses all web push notifications (this event will be fired for each web push notification we show)
  • A notification expires on its own and disappears

Note: This event does not occur if a user clicks on the notification body or one of the action buttons. That is considered a notification click (see the Click event above).

This event is fired on your page. If multiple browser tabs are open to your site, this event will be fired on all pages on which OneSignal is active.

ParameterTypeDescription
notificationNotificationThe OneSignal notification ID of the notification that was just displayed.
function notificationDismissedListener(event) {
  console.log(`dismiss event: ${event}`);
}

OneSignalDeferred.push(function() {
  OneSignal.Notifications.addEventListener("dismiss", notificationDismissedListener);
});

Notification permission changed

Event occurs when the user clicks Allow or Block or dismisses the browser's native permission request.

ParameterTypeDescription
permissionbooleanThe new permission state for push notifications
function permissionChangeListener(permission) {
  if (permission) {
    console.log(`permission accepted!`);
  }
}

OneSignalDeferred.push(function() {
  OneSignal.Notifications.addEventListener("permissionChange", permissionChangeListener);
});

Notification permission prompt displayed

Event occurs when the browser's native permission request has just been shown.

function promptListener() {
  console.log(`permission prompt dispslayed event: ${event}`);
}

OneSignalDeferred.push(function() {
  OneSignal.Notifications.addEventListener("permissionPromptDisplay", promptListener);
});


Slidedown Prompts

Display the OneSignal Slide Prompt on your sites. This type of prompt slides down from the top of the browser viewport on Desktop and up from the bottom on mobile devices. For more details, please refer to Prompting behavior if declined.

📘

Does not replace native browser prompt

This does not replace the Native Browser Prompt required for subscription. You must obtain permissions using the native browser prompt.

Prompt behavior

When declined, future calls will be ignored for at least three days. Further declines will lengthen the time required to elapse before prompting the user again – refer to our guide for more info on dismissing web promps.

To override this back-off behavior to prompt the user again, you can pass {force: true}. However, to provide a good user experience, bind the action to a UI-initiated event like a button click.

Prompt for notification permission

Displays the notification permission prompt.

OneSignalDeferred.push(function() {
  OneSignal.Slidedown.promptPush();
});

Prompt with Categories

Displays the notification permission prompt for notification categories.

OneSignalDeferred.push(function() {
  OneSignal.Slidedown.promptPushCategories();
});

Prompt users to subscribe to SMS messages

Displays the SMS subscription prompt.

OneSignalDeferred.push(function() {
  OneSignal.Slidedown.promptSms();
});

Prompt users to subscribe to email

Displays the email subscription prompt.

OneSignalDeferred.push(function() {
  OneSignal.Slidedown.promptEmail();
});

Prompt users to subscribe to email and SMS simultaneously

Displays the SMS and email subscription prompts.

OneSignalDeferred.push(function() {
  OneSignal.Slidedown.promptSmsAndEmail();
});

Listen to events on the Slidedown prompt

Adds an event listener for the slidedownShown event. The listener function takes a boolean parameter.

function slidedownEventListener(wasShown) {
	console.log(`Slidedown shown event ${wasShown}`);
}

OneSignalDeferred.push(function() {
  OneSignal.Slidedown.addEventListener("slidedownShown", slidedownEventListener);
});

Remove event handlers

Removes an event listener for the slidedownShown event.

function slidedownEventListener(didShow) { // ... }

OneSignalDeferred.push(function() {
  OneSignal.Slidedown.removeEventListener(slidedownEventListener);
});


Push Subscription

Subscription ID

The user's push subscription ID. See Subscriptions for more details.

OneSignalDeferred.push(function() {
  OneSignal.User.PushSubscription.id;
});

Push Token

The subscription's push token. Required to receive push notifications.

OneSignalDeferred.push(function() {
  OneSignal.User.PushSubscription.token;
});

Disable a push subscription

Changes the subscription status of an opted-in push subscription to opted-out. The push subscription cannot get push notifications anymore until optIn() is called or use Update subscription API with enabled: true.

This method does not remove or invalidate push tokens. It is designed for sites that wish to have more granular control of which users receive notifications, such as when implementing notification preference pages.

The user's push subscription can only be opted-out if OneSignal.Notifications.permission is true.

OneSignalDeferred.push(function() {
  OneSignal.User.PushSubscription.optOut();
});

Enable a push subscription

If you previously called the optOut() method, this changes the subscription status to opted-in. If the push token on the subscription is valid, the user should be able to get push notifications again.

This method does not trigger the website prompts and does not set or validate push tokens. It is designed for sites that wish to have more granular control of which users receive notifications, such as when implementing notification preference pages.

The user's push subscription can only be changed back to opted-in if both conditions are met:

  1. OneSignal.Notifications.permission is true.
  2. the optOut() method was previously used.
OneSignalDeferred.push(function() {
  OneSignal.User.PushSubscription.optIn();
});

Check push subscription status

Returns true or false based on the current push subscription status.

OneSignalDeferred.push(function() {
  OneSignal.User.PushSubscription.optedIn;
});

Listen to changes on the push subscription

The change listener is fired when any of the fields on the subscription change. The event includes both the current and the previous state.

ParameterTypeDescription
previousPushSubscriptionNamespacePropertiesThe old push subscription state
currentPushSubscriptionNamespacePropertiesThe new push subscription state

PushSubscriptionNamespaceProperties

ParameterTypeDescription
idstringThe push subscription id.
tokenstringThe token used to target notifications.
optedInbooleanFalse if the push permissions were denied or optOut() was called.
function pushSubscriptionChangeListener(event) {
  if (event.current.token) {
    console.log(`The push subscription has received a token!`);
    //this is a good place to call OneSignal.login and pass in your user ID
  }
}

OneSignalDeferred.push(function() {
  OneSignal.User.PushSubscription.addEventListener("change", pushSubscriptionChangeListener);
});


Email

OneSignal's Mobile and Web SDKs provide methods for collecting emails, logging out of emails, and tracking email subscription changes.

See Email SDK Methods for more details.


SMS

OneSignal's Mobile and Web SDKs provide methods for collecting phone numbers, logging out phone numbers, and tracking SMS subscriptions.

See SMS SDK Methods for more details.


Debugging

Enable logging to help debug if you run into an issue setting up OneSignal. This selector is static, so you can call it before initializing OneSignal. For more info, see Debugging with Browser DevTools.

Set the log level

Set the logging level to print to the DevTools console.

OneSignal.Debug.setLogLevel(“trace”);

Additional log levels

  • 'trace'
  • 'debug'
  • 'info'
  • 'warn'
  • 'error'