Complete API reference for OneSignal Web SDK v16 with initialization, user management, push notifications, slidedown prompts, and debugging methods. Learn how to implement web push notifications, manage user subscriptions, and integrate email/SMS features.
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()
<head>
tag once on each page of your site. The ONESIGNAL_APP_ID
can be found in Keys & IDs.
Parameter | Type | Description |
---|---|---|
appId | String | Required: Your OneSignal App ID found in Keys & IDs. |
requiresUserPrivacyConsent | Boolean | Delays SDK initialization until the user provides privacy consent. Must call setConsentGiven() to complete setup. |
safari_web_id | String | The Safari Web ID for your uploaded Safari .p12 certificate. Web Quickstart. |
promptOptions | Object | Customize the permission prompts. Details below. |
notifyButton | Object | Enable and configure the Subscription Bell. Details below. |
welcomeNotification | Object | Customize or disable the welcome notification. Details below. |
persistNotification | Boolean | Chrome (desktop only) - true : notification persists until clicked, false : disappears after a short time. Firefox/Safari ignore this setting. |
webhooks | Object | Configure event callbacks. See Webhooks. |
autoResubscribe | Boolean | Recommended: Auto-resubscribes users who clear browser cache or migrate to OneSignal. Overrides dashboard setting if used in code. |
notificationClickHandlerMatch | String | "exact" (default): focuses tab with an exact URL match. "origin" : focuses any tab with the same domain. |
notificationClickHandlerAction | String | "navigate" (default): navigates to launchURL . "focus" : focuses existing tab (only used with "origin" match). |
serviceWorkerParam | Object | Set the scope of the service worker. Must be different from other service worker’s scope if applicable. Example:{ scope: "/myPath/myCustomScope/" } |
serviceWorkerPath | String | Set the location of the OneSignal service worker file. Example:"myPath/OneSignalSDKWorker.js" |
promptOptions
parameterspromptOptions
to localize or customize the user permission prompts. All fields are optional.
Parameter | Type | Description |
---|---|---|
slidedown | Object | Contains an array of prompts with configuration options. |
prompts | Array of Objects | An array of prompt configurations. Example:"slidedown": { "prompts": [{...}, {...}] } |
type | String | Prompt types:
|
autoPrompt | Boolean |
|
delay | Object | Controls when auto-prompt is shown:{ pageViews: 3, timeDelay: 20 } = Show after 3rd pageview and 20s wait. |
text | Object | Custom text options:
|
categories | Array of Objects | Only for type: category . Each object includes:tag : internal keylabel : user-visible nameExample: [ {tag: "local_news", label: "Local News"} ] . See Data Tags. |
notifyButton
parametersParameter | Type | Description |
---|---|---|
enable | Boolean | Enables the Subscription Bell. Disabled by default. |
displayPredicate | Function | Custom function (or Promise) that returns true or false to show/hide the Bell. Evaluated once when shown. |
size | String | 'small' , 'medium' , or 'large' . Shrinks to 'small' after subscription. |
position | String | 'bottom-left' or 'bottom-right' . |
offset | Object | CSS pixel offsets: { bottom: '50px', left: '10px' } |
prenotify | Boolean | If true , shows a “1 unread” icon and custom hover text. |
showCredit | Boolean | Set to false to hide “Powered by OneSignal” in the popup. |
text | Object | Custom text for the bell UI. |
welcomeNotification
parametersParameter | Type | Description |
---|---|---|
disable | Boolean | Disable welcome notification. |
message | String | Required: Notification message. Defaults to 'Thanks for subscribing!' if blank. |
title | String | Notification title. Defaults to site title. Use ' ' (space) to remove (not recommended). |
url | URL | Optional URL to open when the user clicks the notification. Typically not needed. |
setLogLevel()
'trace'
'debug'
'info'
'warn'
'error'
login()
with your unique user identifier.
login(external_id)
external_id
. Ensures that all Subscriptions and properties associated with this external_id
are unified under a single onesignal_id
. See Users for more details.
Key behaviors:
external_id
already exists, the SDK switches to that user. Anonymous data collected before login is not merged and will be discarded.external_id
does not exist, the local state will be saved under the current onesignal_id
. Any data collected while the user was anonymous will be kept.login
every time the app identifies a user. logout()
external_id
from the current push subscription.login
method.OneSignal.User.onesignalId
null
if called before user state is initialized. Instead, use User State addObserver()
to listen for user state changes.
OneSignal.User.externalId
null
if not set or called before user state is initialized. Instead, use User State addObserver()
to listen for user state changes.
addEventListener()
User StateaddAlias()
, addAliases()
, removeAlias()
, removeAliases()
external_id
with login()
before adding aliases. Aliases added to subscriptions without external_id
will not sync across multiple subscriptions.getLanguage()
, setLanguage()
key : value
pairs of string data you set on users based on events or user properties. See Data Tags for more details.
addTag()
, addTags()
removeTag()
, removeTags()
getTags()
login()
or new app sessions.
setConsentRequired()
requiresUserPrivacyConsent: true
to the init
method.
setConsentGiven()
setConsentRequired()
or requiresUserPrivacyConsent
is set to true
, our SDK will not be fully enabled until setConsentGiven
is called with true
.setConsentGiven
is set to true
and a Subscription is created, then later it is set to false
, that Subscription will no longer receive updates. The current data for that Subscription remains unchanged until setConsentGiven
is set to true
again.User.PushSubscription.id
null
if called too early. Its recommended to get this data within the subscription observer to react to changes.
User.PushSubscription.token
null
if called too early. Its recommended to get this data within the subscription observer to react to changes.
addEventListener()
push subscription changesoptedIn
value changes (e.g. called optIn()
or optOut()
)onPushSubscriptionChange
event. Your listener receives a state object with the previous
and current
values so you can detect exactly what changed.
To stop listening for updates, call the associated removeObserver()
or removeEventListener()
method.
optOut()
, optIn()
, optedIn
subscribed
or unsubscribed
) of the current push Subscription. Use these methods to control the push subscription status on your site. Common use cases: 1) Prevent push from being sent to users that log out. 2) Implement a notification preference center within your site.
optOut()
: Sets the current push subscription status to unsubscribed (even if the user has a valid push token).optIn()
: Does one of three actions:
subscribed
.optedIn
: Returns true
if the current push subscription status is subscribed, otherwise false
. If the push token is valid but optOut()
was called, this will return false
.addEmail()
, removeEmail()
addEmail
after login()
to set the correct user context. Compatible with Identity Verification.
addSms()
, removeSms()
addSms
after login()
to set the correct user context. Compatible with Identity Verification.
{force: true}
to the method. However, to provide a good user experience, bind the action to a UI-initiated event like a button click.promptPush()
promptPushCategories()
instead.promptPushCategories()
promptPush()
instead.promptSms()
promptEmail()
promptSmsAndEmail()
addEventListener()
SlidedownrequestPermission()
isPushSupported()
true
if the current browser supports web push.
OneSignal.Notifications.permission
true
: The user has granted permission to display notifications.false
: The user has either denied or not yet granted permission to display notifications.optOut
status or the existence of the Subscription ID and Push Token, see OneSignal.User.PushSubscription
for these.
To listen for changes in permission, use the permissionChange
event.
addEventListener()
notificationsaddEventListener
lets you add an arbitrary number of event handlers for notification events.
To stop listening for events, call the associated removeEventListener()
method.
permissionChange
permissionPromptDisplay
click
foregroundWillDisplay
dismiss
click
event.setDefaultUrl()
setDefaultTitle()
sendOutcome()
string
, required) and a value (number
, optional). Each time sendOutcome
method is invoked with the same outcome name passed, the outcome count will increase, and the outcome value will be increased by the amount passed in (if included). See Custom Outcomes for more details.
sendUniqueOutcome()
string
, required). sendUniqueOutcome
will increase the count for that outcome only once per user. See Custom Outcomes for more details.