OneSignal Web Push SDK Reference. Works with Chrome, Firefox, and Safari.
OneSignalSDK.js
with the async
flag so your page load times donโt increase. To use it, place the following code before calling any other OneSignal functions.
OneSignal.push(["functionName", param1, param2]);
OneSignal.push(function() { OneSignal.functionName(param1, param2); });
isPushNotificationsSupported
. Option 2 also lets you call as many OneSignal functions as you need inside the passed-in function block.
init
options
are as follows:
Parameter | Type | Description |
---|---|---|
appId | String | Required: Your OneSignal app id found on the settings page at onesignal.com. |
subdomainName | String | Required on HTTP ONLY: This must match the label you entered in Site Settings. |
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. |
promptOptions | JSON | Localize the HTTP popup prompt. See below details. |
welcomeNotification | JSON | Customize or disable the welcome notification sent to new site visitors. 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. |
autoRegister | Boolean | Not Recommended: Shows Native Browser Prompt immediately. We do not recommend using because it creates a poor user experience. Should be removed from code. |
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 addListenerForNotificationOpened 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 addListenerForNotificationOpened 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
parameterspromptOptions
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 |
---|---|---|
actionMessage | String | Text that says โwants to show notificationsโ by default. Limited to 90 characters. |
exampleNotificationTitleDesktop | String | Text that says โThis is an example notificationโ. Displays on non-mobile devices. Only one line is allowed. |
exampleNotificationMessageDesktop | String | Text that says โNotifications will appear on your desktopโ. Displays on non-mobile devices. Only one line is allowed. |
exampleNotificationTitleMobile | String | Text that says โThis is an example notificationโ. Displays on mobile devices with limited screen width. Only one line is allowed. |
exampleNotificationMessageMobile | String | Text that says โNotifications will appear on your deviceโ. Displays on mobile devices with limited screen width. Only one line is allowed. |
exampleNotificationCaption | String | Text that says โ(you can unsubscribe anytime)โ. |
acceptButton - Slide Prompt acceptButtonText - HTTP PopUp Prompt | String | Customize the โContinueโ text. Limited to 15 characters. |
cancelButton - Slide Prompt cancelButtonText - HTTP PopUp Prompt | String | Customize the โCancelโ text. Limited to 15 characters. |
showCredit | Boolean | Set to false to hide the OneSignal logo. |
welcomeNotification
parameterswelcomeNotification
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
parametersnotifyButton
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. See Hiding the Subscription Bell for an example. |
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. |
init()
.
subdomainName
ParametersetDefaultNotificationUrl
MethodParameter | Type | Description |
---|---|---|
url | String | page url to open from notifications |
setDefaultTitle
MethodParameter | Type | Description |
---|---|---|
title | String | String to set as a default title on notifications |
provideUserConsent
MethodrequiresUserPrivacyConsent: 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.
showNativePrompt
Methodmylabel.os.tc/subscribe
to prompt the user to subscribe to push notifications. Call this in response to a user action like a button or link that was just clicked, otherwise the browserโs popup blocker will prevent the popup from opening.
registerForPushNotifications
MethodpermissionPromptDisplay
EventshowSlidedownPrompt
Method{force: true}
. To provide a good user experience however ONLY do this from an action taken on your site to avoid unexpected prompts.
showCategorySlidedown
MethodgetNotificationPermission
EventParameter | Type | Description |
---|---|---|
callback | function | A callback function that will be called when the browserโs current notification permission has been obtained, with one of โdefaultโ, โgrantedโ, or โdeniedโ. |
isPushNotificationsSupported
MethodisPushNotificationsEnabled
MethodPromise
that resolves to true
if the user has already accepted push notifications and successfully registered with Googleโs FCM server and OneSignalโs server (i.e. the user is able to receive notifications).
If you used OneSignal.setSubscription()
or unsubscribed using the Bell Prompt or Custom Link prompt after the user successfully subscribes through the browser, isPushNotificationsEnabled
will show whatever value you set for setSubscription
.
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 you are still subscribed to the siteโs notifications). Follow Clearing your cache and resetting push permissions to reset the browser data.
Parameter | Type | Description |
---|---|---|
isPushNotificationsEnabledCallBack | Function | Callback to be fired when the check completes. The first parameter of the callback is a boolean value indicating whether the user can receive notifications. |
subscriptionChange
Eventtrue
when:
OneSignal.setSubscription()
is used to opt the user in and outOneSignal.setSubscription()
, which is used to temporarily opt-out the user from receiving notifications by setting a flag on our system so that notifications are not delivered to the user.
To detect changes when using the OneSignal.setSubscription()
flag, you would use the OneSignal.isPushNotificationsEnabled()
method but this will not get called until the page is refreshed.
Parameter | Type | Description |
---|---|---|
subscribed | Boolean | Set to true if the user is currently subscribed; otherwise set to false . |
notificationPermissionChange
EventParameter | Type | Description |
---|---|---|
event | Hash | A JavaScript object with a to property. If to is "granted" , the user has allowed notifications. If to is "denied" , the user has blocked notifications. If to is "default" , the user has clicked the โXโ button to dismiss the prompt. |
popoverShown
- Slide Prompt has just animated into view and is being shown to the user.
popoverAllowClick
- The โContinueโ button on the Slide Prompt was clicked.
popoverCancelClick
- The โNo Thanksโ button on the Slide Prompt was clicked.
popoverClosed
- The Slide Prompt was just closed.
customPromptClick
EventParameter | Type | Description |
---|---|---|
event | Hash | A JavaScript object with a result property. - If result is denied , the user clicked No Thanks on the HTTP Pop-Up Prompt. Popup window closes after this. - If result is granted , the user clicked Continue on the HTTP Pop-Up Prompt. |
granted
, since our SDK will automatically click Continue on the popup window for the user. You should therefore ignore this event if you are using the Slide Prompt.
getUserId
MethodPromise
that resolves to the stored OneSignal subscription ID of the Push Record if one is set, otherwise the Promise resolves to null
. If the user isnโt already subscribed, this function will resolve to null
immediately.
If youโre getting the subscription ID after the user subscribes, call this within the subscriptionChange
event, and check that subscriptionChange
is true
.
If youโre getting the subscription ID on page load, check that the user is subscribed to notifications (e.g. isPushNotificationsEnabled()
).
For custom implementations involving our REST API, associate this OneSignal subscription ID with your data.
Once created, the subscription ID will not change. If the user unsubscribes from web push, for example by clearing their browser data, and resubscribes, a new subscription ID will be created and a new entry will be stored on your appโs users list. The old entry will be unsubscribed and not be automatically deleted.
Parameter | Type | Description |
---|---|---|
callback | function | A callback function which sets the first parameter to the stored Push Recordโs OneSignal subscription ID if one is set, otherwise the first parameter is set to null. |
subscription_id
. A single user can have multiple subscription_id
records based on how many devices, email addresses, and phone numbers they use to interact with your app/site.
You can combine subscription_id
records in OneSignal under a unique User Id called the external_id
.
See the External User Ids guide for more details.
If you have a backend server, we strongly recommend using Identity Verification with your users. Your backend can generate an identifier authentication token and send it to your site.
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.
sendSelfNotification
MethodParameter | Type | Description |
---|---|---|
title | String | The notificationโs title. Currently defaults to โOneSignal Test Messageโ if not set. Use a โ โ single space to get around this. Multiple languages are not supported; write the text in the language the current user should receive it in. |
message | String | The notificationโs body content. Required. Multiple languages are not supported; write the text in the language the current user should receive it in. |
url | String | The URL to launch when the notification is clicked. Use a special URL to prevent any URL from launching. Defaults to this special URL if none is set. |
icon | String | The URL to use for the notification icon. |
data | Hash | Additional data to pass for the notification. |
buttons | Array of Hash | See Action Buttons. |
setSubscription
Methodfalse
to temporarily โmuteโ notifications from going to the user. If you previously set this to false, you can set it to true
to โun-muteโ notifications so that the user receives them again.
Parameter | Type | Description |
---|---|---|
unmute | Boolean | true un-mutes any subscribed userfalse mutes any subscribed user |
notificationDisplay
Eventevent
is a JavaScript object hash containing:
Parameter | Type | Description |
---|---|---|
id | UUID | The OneSignal notification ID of the notification that was just displayed. |
heading | String | The notificationโs title. |
content | String | The notificationโs body message, not including the title. |
data | Hash | Custom additional data you send along with the notification. If you did not send any data, this field will not exist and be undefined . |
url | String | The URL that will be opened if the user clicks on the notification. |
icon | String | The URL to the icon used for the notification. This is fetched every time the notification is displayed. |
notificationDisplay
event is only emitted on sites using HTTPS and not available for Safari. Depending on the notification, more fields (e.g. action buttons) can be included in the callback parameter.notificationDismiss
EventaddListenerForNotificationOpened
method).
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.
event
is a JavaScript object hash containing:
Parameter | Type | Description |
---|---|---|
id | UUID | The OneSignal notification ID of the notification that was just displayed. |
heading | String | The notificationโs title. |
content | String | The notificationโs body message, not including the title. |
data | Hash | Custom additional data you send along with the notification. If you did not send any data, this field will not exist and be undefined . |
url | String | The URL that will be opened if the user clicks on the notification. |
icon | String | The URL to the icon used for the notification. This is fetched every time the notification is displayed. |
addListenerForNotificationOpened
EventnotificationClickHandlerMatch: origin
and notificationClickHandlerAction: focus
for different use cases.notificationClickHandlerMatch: 'origin'
If you have an existing tab of your site open, and the clicked notification is also to your site, the existing tab will be used.notificationClickHandlerAction: 'focus'
Instead of navigating the target tab to the notificationโs URL, the tab will be focused. You can perform navigation manually or choose not to navigate.addListenerForNotificationOpened()
to get the details of the notification you just clicked.
addListenerForNotificationOpened()
to get the clicked notificationโs details, or if you installed a callback listener your callback will be invoked.addListenerForNotificationOpened()
to get the details of the notification you just clicked.notificationClickHandlerMatch: 'origin'
addListenerForNotificationOpened()
on the newly navigated tab to get the clicked notificationโs details.notificationClickHandlerAction: 'focus'
addListenerForNotificationOpened()
to get the clicked notificationโs details, or if you installed a callback listener your callback will be invoked.sendSelfNotification()
testing method.
HTTP Integrations
Mostly identical to HTTPS sites above, with the following exceptions:
Due to limitations on HTTP sites:
notificationClickHandlerMatch: 'origin'
, if multiple stale tabs are open to your site, a different tab than the matching tab may be focused.Parameter | Type | Description |
---|---|---|
id | String | The OneSignal notification ID of the notification that was just clicked. |
heading | String | Title set on the notification. |
content | String | The message text the user seen in the notification. |
icon | String | Icon set on the notification. |
url | String | The URL that this notification opened. |
data | Hash | Custom additional data you send along with the notification. If you did not send any data, this field will not exist and be undefined . |
action | String | Describes whether the notification body was clicked or one of the action buttons (if present) was clicked. An empty string means the notification body was clicked, otherwise the string is set to the action button ID. |