Setup & debugging
You may notice the need to wrap your OneSignal calls withOneSignalDeferred.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()
Initializes the OneSignal SDK. This should be called in the <head> tag once on each page of your site. The ONESIGNAL_APP_ID can be found in Keys & IDs.
If you want to delay initialization of the OneSignal SDK, we recommend using our Privacy methods.
| 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 parameters
Use promptOptions 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 parameters
Configure the Subscription Bell (notify button) shown on the page.
| Parameter | 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 parameters
Customize the welcome notification sent after first-time subscription.
| Parameter | 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. |
Example:
setLogLevel()
Set the logging to print additional logs to the console. See Debugging with Browser DevTools for more details.
JavaScript
'trace''debug''info''warn''error'
User identity & properties
When users subscribe to push notifications on your website, OneSignal automatically creates a OneSignal ID (user-level ID) and a Subscription ID (device-level ID). You can associate multiple Subscriptions (e.g., devices, emails, phone numbers) with a single user by callinglogin() with your unique user identifier.
See Users and Subscriptions for more details.
login(external_id)
Sets the current user context to the provided external_id. This links the current device (web push Subscription) to a known user and unifies all future data under a single onesignal_id. Use this method only for identified users (for example, after login or account restore). For anonymous users, do not call login. Instead, track them using their automatically assigned onesignal_id (see OneSignal.User.onesignalId).
What happens when you call login(external_id)
The SDK behaves differently depending on whether the external_id already exists within the OneSignal app.
If the external_id already exists:
- The SDK switches to that existing user.
- You may see a
409 Conflicterror. This is an expected, innocuous error indicating that the External ID already exists within the OneSignal app and can be ignored.
- You may see a
- The current
onesignal_idis discarded and the existingonesignal_idfor that user is loaded. - The current device (web push Subscription) is linked to the existing user.
- Anonymous data collected before login is not merged and is discarded. This includes tags, session data, email/SMS Subscriptions, and other local user properties.
external_id does not exist:
- A new user is created using the current
onesignal_id. - All data collected while the user was anonymous is retained.
- The device (web push Subscription) becomes linked to this new user.
- The SDK automatically retries the login request on network failures or server errors.
- You do not need to implement your own retry logic.
- Call
login(external_id)every page load once you know the user’s ID (for example, after sign-in or session restore). - Call it again whenever the signed-in user changes (account switch).
- Do not call
loginbefore you have a stable, known user identifier.
JavaScript
logout()
Unlinks the current user from the web push Subscription.
- Removes the
external_idfrom the current web push Subscription. Does not remove theexternal_idfrom other Subscriptions. - Resets the
onesignal_idto a new anonymous user. - Any new data (e.g tags, Subscriptions, session data, etc.) will now be set on the new anonymous user until they are identified with the
loginmethod.
Use this when a user signs out of your site and you do not want to send targeted transactional messages to the browser anymore.
JavaScript
OneSignal.User.onesignalId
Retrieves the current user’s onesignal_id stored locally on the browser. This value represents the active user context (OneSignal’s User ID) and can change over time — for example, when you call login(external_id) or when the SDK initializes. If called too early, this method may return null.
This value is not the Subscription ID which is used to identify the browser aka web push Subscription (see User.PushSubscription.id).
When onesignal_id is available:
- After the OneSignal SDK finishes initializing
- After a user is identified with
login(external_id) - After switching users or restoring a session
addObserver() instead of polling.
Common use cases:
In most cases, you will want to use your own External ID set via the login method. However, there are some cases where you may want to use the onesignal_id directly.
- Tracking anonymous users before an External ID is set
- Storing the OneSignal ID in your backend for support or debugging
- Correlating OneSignal users with internal logs
- Displaying the ID for troubleshooting or QA
JavaScript
OneSignal.User.externalId
Retrieve the current user’s External ID saved locally on the browser. May be null if not set via the login method or called before user state is initialized. Instead, use User State addObserver() to listen for user state changes.
JavaScript
addEventListener() User State
Listen for changes in the user context (e.g., login, logout, ID assignment).
JavaScript
addAlias(), addAliases(), removeAlias(), removeAliases()
Aliases are alternative identifiers (like usernames or CRM IDs).
- Set
external_idwithlogin()before adding aliases. Aliases added to subscriptions withoutexternal_idwill not sync across multiple subscriptions. - See Aliases for details.
JavaScript
getLanguage(), setLanguage()
Get and/or override the auto-detected language of the user. See Multi-language messaging for a list of available language codes.
JavaScript
Custom events
Trigger Journeys and Wait Until step activation via a custom event.Custom events require Web SDK
160500+A user should be logged in for custom events to be tracked.name- Required. The name of the event as a string.properties- Optional. Key-value pairs to add to the event. The properties dictionary or map must be serializable into a valid JSON Object. Supports nested values.
os_sdk that will be available to consume. For example, to target events by subscription type, you would access os_sdk.type.
json
trackEvent()
JavaScript
Data tags
Tags are customkey : value pairs of string data you set on users based on events or user properties. See Data Tags for more details.
addTag(), addTags()
Set a single or multiple tags on the current user.
- Values will be replaced if the key already exists.
- Exceeding your plan’s tag limit will cause the operations to fail silently.
JavaScript
removeTag(), removeTags()
Delete a single or multiple tags from the current user.
JavaScript
getTags()
Returns the local copy of the user’s tags. Tags are updated from the server during login() or new app sessions.
JavaScript
Privacy
setConsentRequired()
Enforces user consent before data collection begins. Must be called before initializing the SDK.
This method is the same as adding the requiresUserPrivacyConsent: true to the init method.
JavaScript
setConsentGiven()
Grants or revokes user consent for data collection. Without consent, no data is sent to OneSignal and no subscription is created.
- If
setConsentRequired()orrequiresUserPrivacyConsentis set totrue, our SDK will not be fully enabled untilsetConsentGivenis called withtrue. - If
setConsentGivenis set totrueand a Subscription is created, then later it is set tofalse, that Subscription will no longer receive updates. The current data for that Subscription remains unchanged untilsetConsentGivenis set totrueagain. - If you want to delete the User and/or Subscription data, use our Delete user or Delete subscription APIs.
JavaScript
Subscriptions
A Subscription represents a single messaging channel instance (for example, a browser) and has a unique Subscription ID (OneSignal’s device-level ID). A user can have multiple Subscriptions across devices and platforms. See Subscriptions for more details.User.PushSubscription.id
Retrieves the web push Subscription ID for the current browser, stored locally by the SDK.
This ID uniquely identifies this specific browser’s push channel, not the user. It is commonly used when associating devices or browsers with your backend or debugging delivery issues.
If called before the Subscription is created or restored, this value may be null.
To reliably detect when the web push Subscription ID becomes available or changes, use the push Subscription listener.
JavaScript
User.PushSubscription.token
Returns the current push subscription token. May return null if called too early. Its recommended to get this data within the subscription observer to react to changes.
JavaScript
addEventListener() Push Subscription Changes
Use this method to respond to push subscription changes like:
- The device receives a new push token from Google (FCM) or Apple (APNs)
- OneSignal assigns a subscription ID
- The
optedInvalue changes (e.g. calledoptIn()oroptOut()) - The user toggles push permission in system settings, then opens the app
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.
JavaScript
optOut(), optIn(), optedIn
Control the subscription status (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:- If the Subscription has a valid push token, it sets the current push subscription status to
subscribed. - If the Subscription does not have a valid push token, it attempts to display the push permission prompt.
- If the Subscription has a valid push token, it sets the current push subscription status to
optedIn: Returnstrueif the current push subscription status is subscribed, otherwisefalse. If the push token is valid butoptOut()was called, this will returnfalse.
JavaScript
addEmail(), removeEmail()
Adds or removes an email Subscription (email address) for the current user.
These methods are compatible with Identity Verification.
When you call addEmail(email):
- The email address becomes an email Subscription for the current user.
- The email may be created or reassigned.
- The same email address cannot exist multiple times in the same OneSignal app. If you see duplicate email addresses, check your REST API requests and contact support if needed.
| Status code | Meaning |
|---|---|
| 200 OK | The email Subscription already belongs to the current user. No changes were made. |
| 201 Created | A new email Subscription was created and linked to the user. |
| 202 Accepted | The email Subscription already existed in the app and was moved to the current user. |
removeEmail(email):
- The email Subscription is removed from the current user.
- The current External ID is removed from the email Subscription.
- A new OneSignal ID is assigned to the email Subscription.
- Other Subscriptions (push, SMS, other emails) remain unaffected.
- Call
login()first, then calladdEmail(). Otherwise, the email may be attached to an anonymous user. - Use a stable, verified email address.
- Follow Email reputation best practices.
JavaScript
addSms(), removeSms()
Adds or removes an SMS Subscription (phone number) for the current user. Phone numbers must be provided in E.164 format (for example, +15551234567).
These methods are compatible with Identity Verification.
When you call addSms(phoneNumber):
- The phone number becomes an SMS Subscription for the current user.
- The number may be created or reassigned.
- The same phone number cannot exist multiple times in the same OneSignal app. If you see duplicate phone numbers, check your REST API requests and contact support if needed.
| Status code | Meaning |
|---|---|
| 200 OK | The SMS Subscription already belongs to the current user. No changes were made. |
| 201 Created | A new SMS Subscription was created and linked to the user. |
| 202 Accepted | The SMS Subscription already existed in the app and was moved to the current user. |
removeSms(phoneNumber):
- The SMS Subscription is removed from the current user.
- The current External ID is removed from the SMS Subscription.
- A new OneSignal ID is assigned to the SMS Subscription.
- Other Subscriptions (push, email, other SMS) remain unaffected.
- Call
login()first, then calladdSms(). Otherwise, the SMS Subscription may be attached to an anonymous user. - Always validate and normalize phone numbers to E.164 format before sending.
- Follow SMS Registration Requirements.
JavaScript
Slidedown prompts
Display the various slidedown prompts on your sites. See Web permission prompts for more details.- If dismissed, future calls will be ignored for at least three days. Further declines will lengthen the time required to elapse before prompting the user again.
- To override back-off behavior, pass
{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()
Displays the regular slidedown prompt for push notifications.
- If using categories, call
promptPushCategories()instead. - Subject to backoff logic set by the OneSignal. See Web permission prompts for more details.
JavaScript
promptPushCategories()
Displays the category slidedown prompt, allowing users to update their tags. Also triggers the native notification permission prompt if the user has not already granted permission.
- If not using categories, call
promptPush()instead. - Subject to backoff logic set by the OneSignal. See Web permission prompts for more details.
JavaScript
promptSms()
Displays the SMS subscription prompt.
- Subject to backoff logic set by the OneSignal. See Web permission prompts for more details.
JavaScript
promptEmail()
Displays the email subscription prompt.
- Subject to backoff logic set by the OneSignal. See Web permission prompts for more details.
JavaScript
promptSmsAndEmail()
Displays the SMS and email subscription prompts simultaneously.
- Subject to backoff logic set by the OneSignal. See Web permission prompts for more details.
JavaScript
addEventListener() Slidedown
Add a callback to detect the Slidedown prompt shown event.
JavaScript
Push notifications
requestPermission()
Requests push notifications permission via the native browser prompt. Subject to backoff logic set by the browser. See Web permission prompts for more details.
JavaScript
isPushSupported()
Returns true if the current browser supports web push.
JavaScript
OneSignal.Notifications.permission
Returns a boolean indicating the site’s current permission to display notifications.
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.
JavaScript
addEventListener() Notifications
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.
To stop listening for events, call the associated removeEventListener() method.
JavaScript
permissionChange
This event occurs when the user clicks Allow or Block or dismisses the browser’s native permission request.
JavaScript
permissionPromptDisplay
This event occurs when the browser’s native permission request has just been shown.
JavaScript
click
This event will fire when the notification’s body/title or action buttons are clicked.
JavaScript
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.
JavaScript
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
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 event.JavaScript
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.
JavaScript
setDefaultTitle()
Sets the default title to display on notifications.
JavaScript
Outcomes
sendOutcome()
Triggers an outcome which can be viewed in the OneSignal dashboard. Accepts an outcome name (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.
JavaScript
sendUniqueOutcome()
Triggers an outcome which can be viewed in the OneSignal dashboard. Accepts only the outcome name (string, required). sendUniqueOutcome will increase the count for that outcome only once per user. See Custom Outcomes for more details.
JavaScript