OneSignal Help & Documentation

Welcome to the OneSignal New IA developer hub. You'll find comprehensive guides and documentation to help you start working with OneSignal New IA as quickly as possible, as well as support if you get stuck. Let's jump right in!

Get Started    Support

Web Push SDK

OneSignal Web Push SDK Reference. Works with Chrome, Firefox and Safari.

For Developers
Advanced Topic

Advanced Topic

Most developers would be best served by going through our Web Push SDK setup guide first, which is a more user-friendly starting point than the API.

Initialization

Javascript Flag

Add this flag to your script tag to improve page performance.

Function

Required. Required to perform any other SDK method. Initializes the web SDK.

Function

Set the URL a notification should open to if one is not provided with the notification.

Function

Set the title of a notification if one is not provided, instead of using the last visited page's title.

Registering Push

permissionPromptDisplay

Event

Occurs when the browser's native permission request has just been shown.

Function

Prompt users to subscribe to web push notifications.

Function

Displays the slidedown permission message to prompt users to subscribe.

This slides down from the top of the screen (or up from the bottom on mobile).

Function

Displays the HTTP permission request to prompt users to subscribe.

This appears to users like a native permission request from the browser.

Function

Describes whether the user has granted, denied, or never been prompted for notification permissions.

Function

Describes whether web push is supported in the running browser environment.

Function

Describes whether the user is subscribed to push notifications.

Event

RECOMMENDED Typically used to perform an action after the user is fully subscribed. Also fires when the user unsubscribes.

Analytics

Event

Analytics Only This event does NOT mean the user is fully subscribed; use the Subscription Change event for that instead.

This event tracks the user clicking clicking Allow, Block, or X to dismiss on the browser's native permission request (for HTTP and for HTTPS sites).

popupLoad

Event

The Fullscreen Permission Message popup window to https://subdomain.os.tc is opened and has just loaded.

Event

User clicks "No Thanks" or "Continue" on our Fullscreen Permission Message popup window (not the browser's permission request).

popupClose

Event

The Fullscreen Permission Message popup window to https://subdomain.os.tc has just closed.

popoverShown

Event

Slidedown Permission Message has just animated into view and is being shown to the user.

popoverAllowClick

Event

The "Continue" button on the Slidedown Permission Message was clicked.

popoverCancelClick

Event

The "No Thanks" button on the Slidedown Permission Message was clicked.

popoverClosed

Event

The Slidedown Permission Message was just closed.

User IDs

Function

Get the User ID of the device

Tags

Function

Get tags for the current user.

Function

Set a tag for the current user.

Function

Set multiple tags for the current user.

Function

Remove a tag from the current user.

Function

Remove multiple tags from the current user.

Data

Function

Associate the current user with an anonymized email address.

Sending Notifications

REST API

REST API to schedule or send a notification to a user.

Function

Send a notification to the current user.

Function

Opt users in or out of receiving notifications.

Receiving Notifications

Event

Occurs when a notification is displayed.

Event

Occurs when a notification is dismissed by clicking X on desktop, or swiping away on mobile.

Function

Occurs when a notification's body is clicked, or the action buttons are clicked.

Clicking X or swiping to dismiss does not trigger this event.

Initialization

Loading SDK Asynchronously

Javascript flag - recommended

OneSignal recommends loading 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.

<script src="https://cdn.onesignal.com/sdks/OneSignalSDK.js" async></script>
<script>var OneSignal = OneSignal || [];</script>

Our API functions can be called asynchronously using either:

  1. OneSignal.push(["functionName", param1, param2]);
  2. OneSignal.push(function() { OneSignal.functionName(param1, param2); });

Option 2 must be used for functions that return a value like isPushNotificationsSupported. Option 2 also lets you call as many OneSignal functions as you need inside the passed-in function block.

init

Function

Call this from each page of your site to initialize OneSignal.

Notes:

  • Do not call this method twice. Doing so results in an error.
  • This call is required before any other function can be used.

Init JSON options are as follows:

Parameter
Type
Description

appId

String

Required Your OneSignal app id found on the settings page at onesignal.com.

subdomainName

String

autoRegister

Boolean

For HTTPS sites:
Automatically show browser's native Permission Request. You can pass in false to delay this pop-up and then call registerForPushNotifications to prompt them later.

Omitting this option for HTTPS sites still shows the browser's permission request by default.

For HTTP sites:
Set this explicitly to true to show the HTTP permission message.

path

String

Special Case (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.

httpPermissionRequest

JSON

Localize the HTTP permission request. See below.

promptOptions

JSON

Localize the HTTP popup prompt. See below.

welcomeNotification

JSON

Customize or disable the welcome notification sent to new site visitors. See below.

notifyButton

JSON

Enable and customize the notifyButton. See below.

persistNotification

Boolean

Chrome - Applies only on Chrome Desktop 47+. If false, the notification will disappear roughly after 20 seconds. If true, the notification will be displayed indefinitely until the user interacts with the notification (dismisses it or clicks it). If this optional value is not set, it defaults to true (i.e. notifications by default persist indefinitely).

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.

safari_web_id

String

See our Web Push Setup for how to set up Safari and include this parameter.

Init httpPermissionRequest parameters

Pass in these optional parameters within httpPermissionRequest when initializing to localize the HTTP popup prompt to your custom text and language. All entries are limited in length. Foreign characters accepted. Each parameter except enable is optional, and its default is used when it is not included.

enable

Boolean

Required This must be set to true to use the HTTP permission request.

useCustomModal

Boolean

Special Case Set to false to hide our modal and use your own. You must handle the user clicking on the modal and call OneSignal.registerForPushNotifications({httpPermissionRequest: true}) after.

modalTitle

String

The title of our modal popup after the user clicks Allow on the HTTP permission request. Defaults to "Thanks for subscribing".

modalMessage

String

The body text of our modal popup after the user clicks Allow on the HTTP permission request. Defaults to "You're now subscribed to notifications. You can unsubscribe at any time."

modalButtonText

String

The Finish button text of our modal popup after the user clicks Allow on the HTTP permission request. Defaults to "Finish Subscribing!".

Init promptOptions parameters

Pass in these optional parameters within promptOptions when initializing to localize the HTTP popup prompt 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 75 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)'.

acceptButtonText

String

Text that says 'CONTINUE'.

cancelButtonText

String

Text that says 'NO THANKS'.

showCredit

Boolean

Set to false to hide the OneSignal logo.

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

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.

Init notifyButton parameters

Pass in these optional parameters within notifyButton when initializing to enable and customize the notify button (aka the Subscription Bell). All parameters below are optional. If not set, they will be replaced with their defaults.

Parameter
Type
Description

enable

Boolean

Enable the notify button. The notify button is otherwise disabled by default.

displayPredicate

Function

A function you define that returns true to show the notify button, 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 notify button after the user is subscribed.

This function is not re-evaluated on every state change; this function is only evaluated once when the notify button begins to show.

See Hiding the Notify Button for an example.

size

String

One of 'small', 'medium', or 'large'. The notify button 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 notify button 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 notify button will display an icon that there is 1 unread message. When hovering over the notify button, the user will see custom text set by message.prenotify.

showCredit

Boolean

Set false to hide the 'Powered by OneSignal' text in the notify button dialog popup.

text

JSON

Customize the notify button text. See the example code below to know what to change.

The following is a basic template of how you would call init(). See our Web Push Prompts page to see additional examples.

// OneSignal is defined as an array here and uses push calls to support OneSignalSDK.js being loaded async.
var OneSignal = OneSignal || [];

OneSignal.push(["init", {
  appId: "YOUR_APP_ID",
  // Your other init settings
}]);

setDefaultNotificationUrl

Function - Chrome · Firefox

Pass in the full URL of the default page you want to open when a notification is clicked. When creating a notification, any URL you specify will take precedence and override the default URL. However if no URL is specified, this default URL specified by this call will open instead. If no default URL is specified at all, the notification opens to the root of your site by default.

Safari - This function is not available. Instead, the default notification icon URL is the Site URL you set in your Safari settings.

Parameter
Type
Description

url

String

page url to open from notifications

OneSignal.push(function() {
  /* These examples are all valid */
  OneSignal.setDefaultNotificationUrl("https://example.com");
  OneSignal.setDefaultNotificationUrl("https://example.com/subresource/resource");
  OneSignal.setDefaultNotificationUrl("http://subdomain.example.com:8080/a/b");
});

setDefaultTitle

Function

Sets the default title to display on notifications. 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.

Parameter
Type
Description

title

String

String to set as a default title on notifications

OneSignal.push(function() {
  OneSignal.setDefaultTitle("My Title");
});

Registering Push

registerForPushNotifications

Function

HTTP Sites: Opens a popup window to subdomain.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.

HTTPS Sites: You may call this at any time to show the prompt for push notifications. If notification permissions have already been granted, nothing will happen.

HTTPS Sites (Optional): Instead of directly prompting the browser's native permission prompt, you may instead use modalPrompt to show a full-screen modal with an image of a notification and show the user what to expect.

See the subscriptionChange event to know when the user has successfully subscribed.

Parameter
Type
Description

modalPrompt

Boolean

Shows a modal popup window on your page explaining and showing an example notification with an option to continue or cancel before showing the native notification prompt to accept notifications. (Option is only available for HTTPS when not using a subdomain. Otherwise a popup window will show with the same results.)

OneSignal.push(function() {
  OneSignal.registerForPushNotifications();
});

OneSignal.push(function() {
  OneSignal.registerForPushNotifications({
    modalPrompt: true
  });
});

showHttpPrompt

Function

Shows the slidedown permission message for HTTP site users to subscribe to notifications. This slides down from the top (or up from the bottom on mobile). Please see Slidedown Permission Message for more details.

OneSignal.push(function() {
  OneSignal.showHttpPrompt();
});

showHttpPermissionRequest

Function

Shows the HTTP permission request for users to subscribe to notifications. To users, this looks like the native browser permission request like on HTTPS sites. Please see HTTP Permission Request for more details.

OneSignal.push(function() {
  OneSignal.showHttpPermissionRequest();
});

getNotificationPermission

Function

Returns a Promise that resolves to the browser's current notification permission as 'default', 'granted', or 'denied'.

You can use this to detect whether the user has allowed notifications, blocked notifications, or has not chosen either setting.

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

OneSignal.push(["getNotificationPermission", function(permission) {
    console.log("Site Notification Permission:", permission);
    // (Output) Site Notification Permission: default
}]);

isPushNotificationsSupported

Function

Returns true if the current browser viewing the page supports push notifications.

Almost all of the API calls on this page internally call this method first before continuing; this check is therefore optional but you may call it if you wish to display a custom message to the user.

This method is synchronous and returns immediately.

OneSignal.push(function() {
  /* These examples are all valid */
  var isPushSupported = OneSignal.isPushNotificationsSupported();
  if (isPushSupported) {
    // Push notifications are supported
  } else {
    // Push notifications are not supported
  }
});

isPushNotificationsEnabled

Function

Returns a Promise that resolves to true if the user has already accepted push notifications and successfully registered with Google's GCM server and OneSignal's server (i.e. the user is able to receive notifications).

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

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.

OneSignal.push(function() {
  /* These examples are all valid */
  OneSignal.isPushNotificationsEnabled(function(isEnabled) {
    if (isEnabled)
      console.log("Push notifications are enabled!");
    else
      console.log("Push notifications are not enabled yet.");    
  });
               
  OneSignal.isPushNotificationsEnabled().then(function(isEnabled) {
    if (isEnabled)
      console.log("Push notifications are enabled!");
    else
      console.log("Push notifications are not enabled yet.");      
  });
});

Subscription Change

Event

Occurs when the user's subscription state changes between unsubscribed and subscribed.

Chrome and Firefox - the user's subscription is true when:

  • Your site is granted notification permissions
  • Your site visitor's web storage database containing OneSignal-related data is intact
  • You have not manually opted out the user from receiving notifications
    • The notify button (aka Subscription Bell) 'Subscribe' and 'Unsubscribe' button opts users in and out without affecting their other subscription parameters
    • OneSignal.setSubscription() is used to opt the user in and out
  • Your site visitor has an installed background web worker used to display notifications

Safari - only the first three are required for a valid subscription.

Use this event to find out when the user has successfully subscribed. The parameter will be set to true to represent a new subscribed state.

A user is no longer subscribed if:

  • The user changes notification permissions
    • The icon next to the URL in the address bar can be clicked to modify site permissions
    • Chrome and Firefox notifications come with a button on the notification to block site notifications
  • The user clears their browser data (clearing cookies will not effect subscription)
  • Another background web worker overwrites our web worker

This event is not related to OneSignal.setSubscription(). OneSignal.setSubscription() 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. This event is more like an event for when OneSignal.isPushNotificationsEnabled() changes.

Callback Event Parameters

Parameter
Type
Description

subscribed

Boolean

Set to true if the user is currently subscribed; otherwise set to false.

OneSignal.push(function() {
  // Occurs when the user's subscription changes to a new value.
  OneSignal.on('subscriptionChange', function (isSubscribed) {
    console.log("The user's subscription state is now:", isSubscribed);
  });
});

This event can be listened to via the on() or once() listener:

// Make sure OneSignal is initialized before listening to the event
var OneSignal = window.OneSignal || [];
OneSignal.push(function() {
  OneSignal.on('(event name here)', function(event) {
    // This callback fires every time the event occurs
  });
  OneSignal.once('(event name here)', function(event) {
    // This callback fires only once when the event occurs, and does not refire
  });
});

Analytics

notificationPermissionChange

Event


Occurs when the user clicks Allow or Block or dismisses the browser's native permission request.

Our web SDK shows different permission messages and requests, and this event is only for the native HTTPS permission request or HTTP permission request.

Callback Event Parameters

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

Special Note: Older versions of desktop Firefox did not have a way to dismiss the prompt, and only had a way to indefinitely delay interacting with the prompt. Current versions of Firefox dismiss the prompt upon clicking anywhere outside of the permission prompt.

OneSignal.push(function() {
  OneSignal.on('notificationPermissionChange', function(permissionChange) {
    var currentPermission = permissionChange.to;
    console.log('New permission state:', currentPermission);
  });
});

customPromptClick

Event

Occurs when the user clicks "No Thanks" or "Continue" on our Fullscreen Permission Message popup window (not the browser's permission request).

Our web SDK shows different permission messages and requests, and this event is best used with only for the Fullscreen Permission Message.

Callback Event Parameters

Parameter
Type
Description

event

Hash

A JavaScript object with a result property.

  • If result is denied, the user clicked No Thanks on the Fullscreen Permission Message. Popup window closes after this.

  • If result is granted, the user clicked Continue on the Fullscreen Permission Message.

Note: If you are using the Slidedown Permission Message, you will always see this event fire with 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 Slidedown Permission Message.

OneSignal.push(function() {
  OneSignal.on('customPromptClick', function(promptClickResult) {
    var promptClickResult = permissionChange.result;
    console.log('Fullscreen Permission Message click result:', promptClickResult);
  });
});

User IDs

getUserId

Function

Returns a Promise that resolves to the stored OneSignal user ID 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 user ID after the user subscribes, call this within the subscriptionChange event, and check that subscriptionChange is true.

If you're getting the user 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 user ID with your data.

Once created, the user ID will not change. If the user unsubscribes from web push, for example by clearing their browser data, and resubscribes, a new user ID will be created and a new entry will be stored on your app's users list. The old entry will not be automatically deleted.

Parameter
Type
Description

callback

function

A callback function which sets the first parameter to the stored OneSignal user ID if one is set, otherwise the first parameter is set to null.

OneSignal.push(function() {
  /* These examples are all valid */
  OneSignal.getUserId(function(userId) {
    console.log("OneSignal User ID:", userId);
    // (Output) OneSignal User ID: 270a35cd-4dda-4b3f-b04e-41d7463a2316    
  });
               
  OneSignal.getUserId().then(function(userId) {
    console.log("OneSignal User ID:", userId);
    // (Output) OneSignal User ID: 270a35cd-4dda-4b3f-b04e-41d7463a2316    
  });
});

Tags

getTags

Function

Retrieve a list of tags that have been set on the user from the OneSignal server.

Parameter
Type
Description

callback

Function

Callback to be fired when the list of tags has been retrieved. The first parameter of the callback is an object containing key-value pairs of the tags.

Returns a Promise that is resolved with the object key-pairs of the tags you sent, or rejected with an error.

OneSignal.push(function() {
  /* These examples are all valid */
  OneSignal.getTags(function(tags) {
    // All the tags stored on the current webpage visitor
  });
               
  OneSignal.getTags().then(function(tags) {
    // All the tags stored on the current webpage visitor
  });
});

tagsReceivedCallBack

Callback

Gets all the tags set on a user from onesignal.com.

Parameter
Type
Description

tags

JSON

JSON object of key value pairs retrieved from the OneSignal server.

OneSignal.push(["getTags", function(tags) {
		console.log("OneSignal getTags:");
		console.log(tags);
	}]);

sendTag

Function

Tag a user based on an app event of your choosing so later you can create segments on onesignal.com to target these users. We recommend using sendTags over sendTag if you need to add or update more than one tag on a user at a time.

You can call OneSignal.push(["sendTag", "key", "value"]) anytime after var OneSignal = OneSignal || [];; you do not have to wait until the user registers. Once the user registers, the tags will automatically be sent to our server as long as the page session is the same (i.e. the user has not navigated to another page).

Parameter
Type
Description

key

String

Key of your choosing to create or update.

value

String

Value to set on the key.
NOTE: Passing in a blank String deletes the key, you can also call deleteTag.

callback

Function

Call back to be fired when the tags have been sent to our server and a response has been returned. The first parameter of the callback is an object of the tags you sent (key-value pairs).

Returns a Promise that is resolved with the object key-pairs of the tags you sent, or rejected with an error.

OneSignal.push(function() {
  /* These examples are all valid */
  OneSignal.sendTag("key", "value");
               
  OneSignal.sendTag("key", "value", function(tagsSent) {
    // Callback called when tags have finished sending
  });
               
  OneSignal.sendTag("key", "value").then(function(tagsSent) {
    // Callback called when tags have finished sending
  });  
});

sendTags

Function

Tag a user based on an app event of your choosing so later you can create segments on onesignal.com to target these users.

You can call OneSignal.push(["sendTags", {key2: "value2", key3: "value3"}]) anytime after var OneSignal = OneSignal || [];; you do not have to wait until the user registers. Once the user registers, the tags will automatically be sent to our server.

Parameter
Type
Description

keyValues

JSON

Key value pairs of your choosing to create or update.
NOTE: Passing in a blank String as a value deletes the key, you can also call deleteTag or deleteTags.

callback

Function

Call back to be fired when the tags have been sent to our server and a response has been returned. The first parameter of the callback is an object of the tags you sent (key-value pairs).

Returns a Promise that is resolved with the object key-pairs of the tags you sent, or rejected with an error.

OneSignal.push(function() {
  /* These examples are all valid */
  OneSignal.sendTags({key: 'value'});
               
  OneSignal.sendTags({
    key: 'value',
    key2: 'value2',
  });

  OneSignal.sendTags({
    key: 'value',
    key2: 'value2',
  }, function(tagsSent) {
    // Callback called when tags have finished sending    
  });

  OneSignal.sendTags({
    key: 'value',
    key2: 'value2',
  }).then(function(tagsSent) {
    // Callback called when tags have finished sending    
  });
});

deleteTag

Function

Deletes a tag that was previously set on a user with sendTag or sendTags. Use deleteTags if you need to delete more than one.

Parameter
Type
Description

key

String

Key to remove.

Returns a Promise that is resolved with the object key-pair of the tag you deleted, or rejected with an error.

OneSignal.push(function() {
  OneSignal.deleteTag("tagKey");
});

deleteTags

Function

Deletes tags that were previously set on a user with sendTag or sendTags.

Parameter
Type
Description

keys

Array

Keys to remove.

callback

Function

Callback to be fired when the list of tags has been removed. The first parameter of the callback is an array of the tags that were deleted.

Returns a Promise that is resolved with the object key-pairs of the tags you deleted, or rejected with an error.

OneSignal.push(function() {
  /* These examples are all valid */
  OneSignal.deleteTags(["key1"]);
               
  OneSignal.deleteTags(["key1", "key2"]);

  OneSignal.deleteTags(["key1", "key2"], function(tagsDeleted) {
    // Callback called when tags have been deleted    
  });

  OneSignal.deleteTags(["key1", "key2"]).then(function(tagsDeleted) {
  });
});

Data

syncHashedEmail

Function - Advanced

This function allows you to provide a user email, which is hashed by our SDK and uploaded to our servers, for better user targeting. Our segments supports targeting of users by hashed email.

Provide a plain text email, which our SDK will then hash using MD5 and SHA1 before being stored.

Returns a Promise that resolves to true after the email has been synced with our servers. If the email is missing, or an invalid email, this Promise rejects with a descriptive error. If the email is unable to be synced, the Promise rejects with the response from the sync attempt.

Parameter
Type
Description

email

String

The user's plain text email address you would like to store as a record on the current user. This is used for better data targeting.

The plain text email will be hashed by our SDK before being transmitted to our server.

OneSignal.push(function() {
  /* 
  	Please be sure to provide a plain-text email here. Our web SDK will hash this email in the browser using MD5 and SHA1 before sending the final hashed email to OneSignal.
  */
  OneSignal.syncHashedEmail("user@example.com");
});

Sending Notifications

Create Notification

To send notifications to users, please see the Create notification REST API docs, or use the Dashboard. Because the Web Push API is run client-side, it does not have the ability to programmatically send to multiple users at once, or users that are not currently on your website.

sendSelfNotification

Function - Advanced

Sends to individual users only

This does not send to all users. Please see our Create notification REST API for sending notifications. This function is primarily for your own internal testing.

Sends a push notification to the current user on the webpage. This is a simplified utility function to send a test message to yourself or a quick message to the user. It does not support any targeting options.

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

OneSignal.sendSelfNotification(
  /* Title (defaults if unset) */
  "OneSignal Web Push Notification",
  /* Message (defaults if unset) */
  "Action buttons increase the ways your users can interact with your notification.", 
   /* URL (defaults if unset) */
  'https://example.com/?_osp=do_not_open',
  /* Icon */
  'https://onesignal.com/images/notification_logo.png',
  {
    /* Additional data hash */
    notificationType: 'news-feature'
  }, 
  [{ /* Buttons */
    /* Choose any unique identifier for your button. The ID of the clicked button is passed to you so you can identify which button is clicked */
    id: 'like-button',
    /* The text the button should display. Supports emojis. */
    text: 'Like',
    /* A valid publicly reachable URL to an icon. Keep this small because it's downloaded on each notification display. */
    icon: 'http://i.imgur.com/N8SN8ZS.png',
    /* The URL to open when this action button is clicked. See the sections below for special URLs that prevent opening any window. */
    url: 'https://example.com/?_osp=do_not_open'
  },
  {
    id: 'read-more-button',
    text: 'Read more',
    icon: 'http://i.imgur.com/MIxJp1L.png',
    url: 'https://example.com/?_osp=do_not_open'
  }]
);

setSubscription

Function - Advanced

Do not use with Notify Button / Subscription Button

This function is not for use with sites that implement the Notify Button (aka Subscription Bell), as this function may override user preferences.

This function is for sites that wish to have more granular control of which users receive notifications, such as when implementing notification preference pages.

This function lets a site mute or unmute notifications for the current user. This event is not related to actually prompting the user to subscribe. The user must already be subscribed for this function to have any effect.

Set to false 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 user
false mutes any subscribed user

Returns a promise that resolves after temporarily opting the user out of receiving notifications by setting a flag on our system so that notifications are not delivered to the user.

OneSignal.push(["setSubscription", false]);

Receiving Notifications

Notification Display

Event - Chrome

Occurs after a notification is visibly displayed on the user's screen.

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.

Callback Event Parameters

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.

Note: Depending on the notification, more fields (e.g. action buttons) can be included in the callback parameter.

OneSignal.on('notificationDisplay', function (event) {
	console.warn('OneSignal notification displayed:', event);
  /*
  {
      "id": "ce31de29-e1b0-4961-99ee-080644677cd7",
      "heading": "OneSignal Test Message",
      "content": "This is an example notification.",
      "url": "https://onesignal.com?_osp=do_not_open",
      "icon": "https://onesignal.com/images/notification_logo.png"
  }
  */
});

This event can be listened to via the on() or once() listener:

// Make sure OneSignal is initialized before listening to the event
var OneSignal = window.OneSignal || [];
OneSignal.on('(event name here)', function(event) {
  // This callback fires every time the event occurs
});
OneSignal.once('(event name here)', function(event) {
  // This callback fires only once when the event occurs, and does not refire
});

Notification Dismiss

Event

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 (please see the addListenerForNotificationOpened method).

Supported On: Chrome 50+ only.

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.

Callback Event Parameters

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.

Note: Depending on the notification, more fields (e.g. action buttons) can be included in the callback parameter.

OneSignal.on('notificationDismiss', function (event) {
	console.warn('OneSignal notification dismissed:', event);
  /*
  {
      "id": "ce31de29-e1b0-4961-99ee-080644677cd7",
      "heading": "OneSignal Test Message",
      "content": "This is an example notification.",
      "url": "https://onesignal.com?_osp=do_not_open",
      "icon": "https://onesignal.com/images/notification_logo.png"
  }
  */
});

This event can be listened to via the on() or once() listener:

// Make sure OneSignal is initialized before listening to the event
var OneSignal = window.OneSignal || [];
OneSignal.on('(event name here)', function(event) {
  // This callback fires every time the event occurs
});
OneSignal.once('(event name here)', function(event) {
  // This callback fires only once when the event occurs, and does not refire
});

addListenerForNotificationOpened

Function/Event Chrome · Firefox

Note: Not supported on Safari.

Note: This event occurs once only. If you would this to occur continuously every time a notification is clicked, please call this method again after your callback fires.

Use this function to:

  • Listen for future clicked notifications
  • Check for notifications clicked in the last 5 minutes

Your callback will execute when the notification's body/title or action buttons are clicked.

The spec below describes:

  • The default behavior
    Events only fire if your URL matches the notification's opening URL exactly; the event will be available on the newly opened tab (and only that opened tab) to the notification's opening URL. See the special flags notificationClickHandlerMatch: origin and notificationClickHandlerAction: focus for different use cases.
  • A special init flag 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.
  • A special init flag 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.

These two optional flags must be placed in the root of your OneSignal initialization options. They will be stored (or removed if missing) on each page load as OneSignal parses the available init options.

HTTPS Sites

  • Default Behavior (no special flags)

    • If no existing site tabs are open, a new tab is opened. You may call addListenerForNotificationOpened() to get the details of the notification you just clicked.
    • If one or more tabs to your site is open:
      • And the clicked notification shares the same URL as one of your site's tab, the existing tab is focused. Call addListenerForNotificationOpened() to get the clicked notification's details, or if you installed a callback listener your callback will be invoked.
      • And the clicked notification's URL is different, a new tab is opened. You may call addListenerForNotificationOpened() to get the details of the notification you just clicked.
  • Using init option notificationClickHandlerMatch: 'origin'

    • If no existing site tabs are open, the behavior is the same as the default (see above).
    • If one or more tabs to your site is open:
      • And the clicked notification shares the same URL as one of your site's tab, the behavior is the same as the default (see above).
      • And the clicked notification's URL is different, the most recently opened tab of your site is focused and navigated to the notification's URL. Call addListenerForNotificationOpened() on the newly navigated tab to get the clicked notification's details.
  • Using init option notificationClickHandlerAction: 'focus'

    • If no existing site tabs are open, the behavior is the same as the default (see above).
    • Any other case: The most recently opened tab of your site is focused only (not navigated away). Call addListenerForNotificationOpened() to get the clicked notification's details, or if you installed a callback listener your callback will be invoked.

HTTP Integrations (using subdomainName as an init option)

Mostly identical to HTTPS sites above, with the following exceptions:

Due to limitations on HTTP sites:

  • If multiple stale tabs are open to your site, a clicked notification sharing an identical URL to an existing tab may not focus the tab and may instead open a new tab.
  • When using 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.

header

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.

OneSignal.push(["addListenerForNotificationOpened", function(data) {
	console.log("Received NotificationOpened:");
	console.log(data);
}]);
/* Do NOT call init twice */
OneSignal.push(["init", {
  /* Your other init settings ... */
  notificationClickHandlerMatch: 'exact', /* See above documentation: 'origin' relaxes tab matching requirements, 'exact' is default */
  notificationClickHandlerAction: 'navigate', /* See above documentation: 'focus' does not navigate the targeted tab, 'navigate' is default */
  /* ... */
}]);

Deprecations and Major Changes

March 21, 2017: Removed getRegistrationId() from documentation. getUserId() should always be used instead.
March 15, 2016: Deprecated getIdsAvailable() in favor of getUserId() and getRegistrationId(). Deprecated idsAvailableCallback in favor of subscriptionChange event.

Web Push SDK

OneSignal Web Push SDK Reference. Works with Chrome, Firefox and Safari.

For Developers
Advanced Topic