Web SDK reference
Web SDK API Reference
Setup
You may notice the need to wrap your OneSignal calls with OneSignalDeferred.push(async 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()
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.
window.OneSignalDeferred = window.OneSignalDeferred || [];
OneSignalDeferred.push(async function(OneSignal) {
await OneSignal.init({
appId: "YOUR ONESIGNAL APP ID",
});
});
Init options are as follows. These only work with Custom Code Setup:
Parameter | Type | Description |
---|---|---|
appId | String | Required: Your OneSignal app id found on the settings page at onesignal.com. |
requiresUserPrivacyConsent | Boolean | Allows 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_id | String | The bundle ID for your Safari p12 certificate uploaded to the OneSignal dashboard. See Web Quickstart. |
promptOptions | JSON | Localize the popup prompts. See below details. |
welcomeNotification | JSON | Customize or disable the welcome notification sent to new site subscribers. See below details. |
notifyButton | JSON | Enable and customize the notifyButton. See below details. |
persistNotification | Boolean | Chrome (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. |
webhooks | JSON | See our Webhooks page for the nested options. |
autoResubscribe | Boolean | Recommended, 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. |
notificationClickHandlerMatch | String | Default: 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. |
notificationClickHandlerAction | String | "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. |
path | String | Special 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
promptOptions
parametersPass 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.
Parameter | Type | Description |
---|---|---|
slidedown | JSON | This object contains an array of prompts with the below options. |
prompts | Array of Objects | Setup multiple prompt types, each as their own object in the prompts array.Example: "slidedown": { "prompts": [{...}, {...}, {...}] } |
type | String | Push 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. |
autoPrompt | Boolean | true will display the prompt based on the delay options.false will prevent the prompt from displaying until the Slidedowns methods are used. |
text | JSON | All 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. |
delay | JSON | - 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. |
categories | Array of Objects | Only 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
welcomeNotification
parametersPass 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.
Parameter | Type | Description |
---|---|---|
disable | Boolean | Disables sending a welcome notification to new site visitors. If you want to disable welcome notifications, this is the only option you need. |
title | String | The 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. |
message | String | Required: 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. |
url | URL | An 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
notifyButton
parametersPass 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.
Parameter | Type | Description |
---|---|---|
enable | Boolean | Enable the Subscription Bell. The Subscription Bell is otherwise disabled by default. |
displayPredicate | Function | A 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. |
size | String | One 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. |
position | String | Either 'bottom-left' or 'bottom-right'. The Subscription Bell will be fixed at this location on your page. |
offset | JSON | Specify CSS-valid pixel offsets using bottom, left, and right. |
prenotify | Boolean | If 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 . |
showCredit | Boolean | Set false to hide the 'Powered by OneSignal' text in the Subscription Bell dialog popup. |
text | JSON | Customize 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(async function(OneSignal) {
await 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()
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 Push subscriptionaddEventListener()
method which triggers when the subscription record status changes.
OneSignalDeferred.push(async function(OneSignal) {
await OneSignal.login("external_id");
});
//Example combining with push subscription change event
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.login("external_id");
}
}
OneSignalDeferred.push(function(OneSignal) {
OneSignal.User.PushSubscription.addEventListener("change", pushSubscriptionChangeListener);
});
logout()
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.
OneSignalDeferred.push(async function(OneSignal) {
await OneSignal.logout();
});
addAlias()
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()
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()
removeAlias()
Remove an alias from the current user.
OneSignal.User.removeAlias("ALIAS_LABEL");
removeAliases()
removeAliases()
Remove aliases from the current user.
OneSignal.User.removeAliases(["ALIAS_LABEL_01", "ALIAS_LABEL_02", "ALIAS_LABEL_03"]);
externalId
externalId
Get the External ID of the currently logged-in user.
OneSignal.User.externalId
onesignalId
onesignalId
Get the OneSignal ID of the currently logged-in user.
OneSignal.User.onesignalId
addEventListener()
User State
addEventListener()
User StateDetect when the user state changes, like when a OneSignal ID or External ID is created/changed.
OneSignalDeferred.push(function() {
OneSignal.User.addEventListener('change', function (event) {
console.log('change', { event });
});
});
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()
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('tag_key', 'tag_value');
addTags()
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()
removeTag()
Remove the data tag with the provided key from the current user.
OneSignal.User.removeTag("KEY");
removeTags()
removeTags()
Remove multiple tags from the current user.
OneSignal.User.removeTags(['KEY_01', 'KEY_02', 'KEY_03']);
getTags()
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()
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()
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()
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()
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()
isPushSupported()
Returns true
if the current browser supports web push.
const isSupported = OneSignal.Notifications.isPushSupported();
permission
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, seeOneSignal.User.PushSubscription
for these.
let permission = 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()
requestPermission()
Requests push notifications permission via the native browser prompt.
Web SDK v15 see showNativePrompt
method.
OneSignal.Notifications.requestPermission();
addEventListener()
Push notification
addEventListener()
Push notificationYou 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
#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.
Parameter | Type | Description |
---|---|---|
notification | Notification | The notification will display. |
function foregroundWillDisplayListener(event) {
console.log(`notification will display: ${notification}`);
}
OneSignal.Notifications.addEventListener("foregroundWillDisplay", foregroundWillDisplayListener);
#dismiss
#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.
Parameter | Type | Description |
---|---|---|
notification | Notification | The OneSignal notification ID of the notification that was just displayed. |
function notificationDismissedListener(event) {
console.log(`dismiss event: ${event}`);
}
OneSignal.Notifications.addEventListener("dismiss", notificationDismissedListener);
#permissionChange
#permissionChange
![](https://files.readme.io/494fb59-Browser_Push_Permission_Request.png)
This event occurs when the user clicks Allow or Block or dismisses the browser's native permission request.
Parameter | Type | Description |
---|---|---|
permission | boolean | The new permission state for push notifications |
function permissionChangeListener(permission) {
if (permission) {
console.log(`permission accepted!`);
}
}
OneSignal.Notifications.addEventListener("permissionChange", permissionChangeListener);
#permissionPromptDisplay
#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
#click
This event will fire when the notification's body/title or action buttons are clicked.
Parameter | Type | Description |
---|---|---|
notification | Notification | An object describing the notification that was clicked. |
result | NotificationClickResult | An 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
removeEventListener()
Push notificationRemoves 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()
promptPush()
Displays the notification permission prompt.
OneSignal.Slidedown.promptPush();
promptPushCategories()
promptPushCategories()
Displays the notification permission prompt for notification categories.
OneSignal.Slidedown.promptPushCategories();
promptSms()
promptSms()
Displays the SMS subscription prompt.
OneSignal.Slidedown.promptSms();
promptEmail()
promptEmail()
Displays the email subscription prompt.
OneSignal.Slidedown.promptEmail();
promptSmsAndEmail()
promptSmsAndEmail()
Displays the SMS and email subscription prompts simultaneously.
OneSignal.Slidedown.promptSmsAndEmail();
addEventListener()
Slidedown
addEventListener()
SlidedownAdd a callback to detect the Slidedown prompt shown event.
OneSignalDeferred.push(function() {
OneSignal.Slidedown.addEventListener('slidedownShown', function (event) {
console.log('slidedownShown', { event });
});
});
Push Subscription
id
id
The user's push subscription ID. See Subscriptions for more details.
OneSignal.User.PushSubscription.id;
token
token
The subscription's push token. Required to receive push notifications.
OneSignal.User.PushSubscription.token;
optOut()
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()
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:
OneSignal.Notifications.permission
istrue
.- the
optOut()
method was previously used.
OneSignal.User.PushSubscription.optIn();
optedIn
optedIn
Returns true
or false
based on the current push subscription status.
OneSignal.User.PushSubscription.optedIn;
addEventListener()
Push subscription
addEventListener()
Push subscriptionThe change listener is fired when any of the fields on the subscription change. The event includes both the current and the previous state.
Parameter | Type | Description |
---|---|---|
previous | PushSubscriptionNamespaceProperties | The old push subscription state |
current | PushSubscriptionNamespaceProperties | The new push subscription state |
PushSubscriptionNamespaceProperties
Parameter | Type | Description |
---|---|---|
id | string | The push subscription id. |
token | string | The token used to target notifications. |
optedIn | boolean | False 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()
addEmail()
Adds an email subscription (email address) 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()
removeEmail()
Deletes the email subscription from the OneSignal App.
OneSignal.User.removeEmail("[email protected]");
SMS
addSms()
addSms()
Adds an 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()
removeSms()
Deletes the SMS subscription from the OneSignal App.
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()
setLogLevel()
Set the logging level to print to the DevTools console.
OneSignal.Debug.setLogLevel(“trace”);
Log levels
'trace'
'debug'
'info'
'warn'
'error'
Updated 2 days ago