Web SDK Reference

Web SDK API Reference

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().

init()

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 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.

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.

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.

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.

login()

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.

OneSignal.login("EID");

logout()

Log out the user previously logged in via thelogin. 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.

OneSignal.logout();

addAlias()

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

OneSignal.User.addAlias("ALIAS_LABEL", "ALIAS_ID");

addAliases()

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

OneSignal.User.addAliases({
  ALIAS_LABEL_01: "ALIAS_ID_01",
  ALIAS_LABEL_02: "ALIAS_ID_02",
  ALIAS_LABEL_03: "ALIAS_ID_03", 
});

removeAlias()

Remove an alias from the current user.

OneSignal.User.removeAlias("ALIAS_LABEL");

removeAliases()

Remove aliases from the current user.

OneSignal.User.removeAliases(["ALIAS_LABEL_01", "ALIAS_LABEL_02", "ALIAS_LABEL_03"]);

getExternalId()

Get the External ID of the currently logged-in user.

One

getOnesignalId()

Gety the OneSignal ID of the currently logged-in user.


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. For example, you can tag a user based on which message they engaged with, so later, you can create Segments or further Personalize Messages. See Data Tags Overview for more details on use cases.

addTag()

Add a tag for the current user. If the tag key already exists, it will be replaced with the value provided here. If you try to set more tags on a user than your plan allows, it will fail. You will need to delete any unwanted tags first before setting or updating tags. See Tags FAQ for details.

OneSignal.User.addTag('my_tag', 'tag');

addTags()

Add multiple tags for the current user. A tag key will be replaced with its corresponding value if it already exists. If you try to set more tags on a user than your plan allows, it will fail. You will need to delete any unwanted tags first before setting or updating tags. See Tags FAQ for details.

OneSignal.User.addTags({ 
 KEY_01: "VALUE_01",
 KEY_02: "VALUE_02",
 KEY_03: "VALUE_03"
});

removeTag()

Remove the data tag with the provided key from the current user.

OneSignal.User.removeTag("KEY");

removeTags()

Remove multiple tags from the current user.

OneSignal.User.removeTags(['KEY_01', 'KEY_02', 'KEY_03']);

getTags()

Requires SDK 5.0.5+

Loads the current user's local tags. Remote tags are pulled and stored locally when the user changes after calling login() or when a new session is started – your app is opened after over 30 seconds of being out-of-focus.

const tags = OneSignal.User.getTags()


Privacy

setConsentRequired()

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.

OneSignal.setConsentRequired(true);

setConsentGiven()

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.

OneSignal.setConsentGiven(true);


Push Notifications

setDefaultUrl()

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.

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.

setDefaultTitle()

Sets the default title to display on notifications.

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.

isPushSupported()

Returns true if the current browser supports web push.

const isSupported = OneSignal.Notifications.isPushSupported();

permission

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.
let permission = await OneSignal.Notifications.permission;

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.

requestPermission()

Requests push notifications permission via the native browser prompt.

Web SDK v15 see showNativePrompt method.

OneSignal.Notifications.requestPermission();

addEventListener() Push 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}`);
}

OneSignal.Notifications.addEventListener("event", eventListener);

#foregroundWillDisplay

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

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

OneSignal.Notifications.addEventListener("foregroundWillDisplay", foregroundWillDisplayListener);

#dismiss

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}`);
}

OneSignal.Notifications.addEventListener("dismiss", notificationDismissedListener);

#permissionChange

This 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!`);
  }
}

OneSignal.Notifications.addEventListener("permissionChange", permissionChangeListener);

#permissionPromptDisplay

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

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

OneSignal.Notifications.addEventListener("permissionPromptDisplay", promptListener);


#click

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}`);
}

OneSignal.Notifications.addEventListener("click", clickEventListener);

removeEventListener() Push notification

Removes the event handler for the given event.

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

OneSignal.Notifications.removeEventListener("event", eventListener);


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.

promptPush()

Displays the notification permission prompt.

OneSignal.Slidedown.promptPush();

promptPushCategories()

Displays the notification permission prompt for notification categories.

OneSignal.Slidedown.promptPushCategories();

promptSms()

Displays the SMS subscription prompt.

OneSignal.Slidedown.promptSms();

promptEmail()

Displays the email subscription prompt.

OneSignal.Slidedown.promptEmail();

promptSmsAndEmail()

Displays the SMS and email subscription prompts simultaneously.

OneSignal.Slidedown.promptSmsAndEmail();

addEventListener() Slidedown

Add a callback to handle Slidedown prompt events.

OneSignal.Slidedown.addEventListener("event"() => console.log("Slidedown event"));

#slidedownShown

This event occurs when the Slidedown prompt is presented to the user.

OneSignal.Slidedown.addEventListener("slidedownShown"() => console.log(`Slidedown shown event ${wasShown}`));

removeEventListener() Slidedown

Removes an event listener for the slidedownShown event.

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

OneSignal.Slidedown.removeEventListener(slidedownEventListener);


Push Subscription

id

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

OneSignal.User.PushSubscription.id;

token

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

OneSignal.User.PushSubscription.token;

optOut()

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.

OneSignal.User.PushSubscription.optOut();

optIn()

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.
OneSignal.User.PushSubscription.optIn();

optedIn

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

OneSignal.User.PushSubscription.optedIn;

addEventListener() 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
  }
}

OneSignal.User.PushSubscription.addEventListener("change", pushSubscriptionChangeListener);


Email

addEmail()

Add a new email subscription to the current user.

OneSignal.User.addEmail("[email protected]");

πŸ“˜

Use Identity Verification

If you have a backend server, we strongly recommend using Identity Verification with your users. Your backend can generate an Email Authentication Token and send it to your app.

removeEmail()

Remove an email subscription from the current user. Returns false if the given email doesn't exist on the user within the SDK, no request will be made.

OneSignal.User.removeEmail("[email protected]");


SMS

addSms()

Add a new SMS subscription (phone number) to the current user. Requires phone numbers to follow the E.164 international telephone number plan.

OneSignal.User.addSms("+15558675309");

πŸ“˜

Use Identity Verification

If you have a backend server, we strongly recommend using Identity Verification with your users. Your backend can generate an SMS Authentication Token and send it to your app or website.

removeSms()

Remove an SMS subscription (phone number) from the current user.

OneSignal.User.removeSms("+15558675309");


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.

setLogLevel()

Set the logging level to print to the DevTools console.

OneSignal.Debug.setLogLevel(β€œtrace”);

Log levels

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