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    Discussions

Cordova SDK

OneSignal Cordova SDK Reference. Works with iOS, Android (and derivatives like Amazon) and Windows Phone 8.1.

For Developers

Just starting with Cordova?

Check out our Cordova SDK Setup guide.

Upgrade to newest SDK

A number the methods and classes below are only available on our newest SDK. To upgrade to the latest Cordova SDK, read the Cordova SDK Setup.

Initialization

Builder Method

Initialize OneSignal

Builder Method

Builder Method

Automatically Display Notifications when app is in focus

Builder Method

iOS - Settings for iOS apps

Builder Method

Complete initialization

Privacy

Method

Determines whether the SDK should delay initialization

Method

Provides privacy consent

Method

Accepts a callback that returns a boolean indicating if the user provided privacy consent

Registering Push

Method

iOS - Display Permissions Prompt for push notifications

Status

Method

Current Permission and Subscription status

Method

Permission status changes

Method

Subscription status changes

Tags

Method

View Tags from a User

Method

Add a Tag to a User

Method

Method

Delete a Tag from a User

Method

Data

Method

Prompt Users for Location

Method

Disable or enable location collection (Defaults to enabled) if your app has location permission

Sending Notifications

Method

Send or schedule a notification to a user

Method

Clear all notifications sent from OneSignal

Method

Opt users in or out of receiving notifications

Receiving Notifications

Handler

When a notification is received by a device

Handler

When a user takes an action on a notification

Class

Information returned from the notification the user received

Class

Notification the user opened

Class

How user opened notification

Class

Data that comes with a notification

Email

Method

Set user's email

Method

Log user out to dissociate email from device

Method

Observer for subscription changes to email

Appearance

Method

When user receives notification, vibrate device less

Method

When user receives notification, do not play a sound

Debug

Method

Enable logging to help debug OneSignal implementation

Initialization

startInit

Builder Method

Starts initialization of OneSignal, call this from the deviceready event.

Parameter
Type
Description

appId

String

Required Your OneSignal app id, available in Keys & IDs.


Example: 5eb5a37e-b458-11e3-ac11-000c2940e62c

window.plugins.OneSignal
  .startInit("YOUR_APPID")
  .endInit();

handleNotificationReceived

Builder Method

Sets a notification received handler. Only called if the app is in focus at the time the notification was received.

Parameter
Type
Description

handler

Instance to a class implementing this interference.

window.plugins.OneSignal
  .startInit("YOUR_APPID")
  .handleNotificationReceived(function(jsonData) {
    alert("Notification received:\n" + JSON.stringify(jsonData));
    console.log('Did I receive a notification: ' + JSON.stringify(jsonData));
  })
  .endInit();

handleNotificationOpened

Builder Method

Sets a notification opened handler. The instance will be called when a notification is tapped on from the notification shade (Android) or notification center (iOS), or when closing an Alert notification shown in the app (if InAppAlert is enabled in inFocusDisplaying, below).

Parameter
Type
Description

handler

Instance to a class implementing this interference.

window.plugins.OneSignal
  .startInit("YOUR_APPID")
  .handleNotificationOpened(function(jsonData) {
    alert("Notification opened:\n" + JSON.stringify(jsonData));
    console.log('didOpenRemoteNotificationCallBack: ' + JSON.stringify(jsonData));   
  })
  .endInit();

inFocusDisplaying

Builder Method

Setting to control how OneSignal notifications will be shown when one is received while your app is in focus. By default this is set to InAppAlert, which can be helpful during development.

Notification - native notification display while user has app in focus (can be distracting).
InAppAlert (Default) - native alert dialog display, which can be helpful during development.
None - notification is silent.

Disable Before Launch

We recommend you set this to none prior to launching your app, so users do not get interrupted while using your app.

Parameter
Type
Description

displayOption

OSInFocusDisplayOption

Options are None, InAppAlert, and Notification.

window.plugins.OneSignal
  .startInit("YOUR_APPID")
  .inFocusDisplaying(window.plugins.OneSignal.OSInFocusDisplayOption.Notification)
  .endInit();

iOSSettings

Builder Method - iOS

Settings keys that can be passed into the initialization chaining method.

Parameter
Type
Description

kOSSettingsKeyAutoPrompt

Boolean

Auto prompt user for notification permissions.

kOSSettingsKeyInAppLaunchURL

Boolean

Launch notifications with a launch URL as an in app webview.

// Set your iOS Settings
var iosSettings = {};
iosSettings["kOSSettingsKeyAutoPrompt"] = true;
iosSettings["kOSSettingsKeyInAppLaunchURL"] = false;

// Initialize
window.plugins.OneSignal
  .startInit("YOUR_APPID")
  .iOSSettings(iosSettings)
  .endInit();

EndInit

Builder Method

Must be called after StartInit to complete initialization of OneSignal. See example above.

Privacy

setRequiresUserPrivacyConsent

Function

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(true) method is called.

If you set this to be true, the SDK will not fully initialize until consent is provided. You can still call OneSignal methods, but nothing will happen, and the user will not be registered for push notifications.

//will delay initialization of the SDK until the user provides consent
window.plugins.OneSignal.setRequiresUserPrivacyConsent(true);

provideUserConsent

Function

If your application is set to require the user's privacy consent, you can provide this consent using this method. Until you call provideUserConsent(true), the SDK will not fully initialize and will not send any data to OneSignal.


function userTappedProvideConsentButton() {
  //will initialize the SDK and register for push notifications
  window.plugins.OneSignal.provideUserConsent(true);
}

userProvidedPrivacyConsent

Function

Accepts a callback, which returns a boolean variable indicating if the user has given privacy consent yet.

window.plugins.OneSignal.userProvidedPrivacyConsent((providedConsent) => {
  //if providedConsent == true, it means the SDK has been initialized and can be used
});

Registering Push

promptForPushNotificationsWithUserResponse

Method - iOS

Prompt the user for notification permissions. Callback fires as soon as the user accepts or declines notifications.

Requirements

Only works if you set kOSSettingsKeyAutoPrompt to false.

Recommendations

You can only prompt once so it is recommend to explain what benefits notifications will give the user.

window.plugins.OneSignal.promptForPushNotificationsWithUserResponse(function(accepted) {
  console.log("User accepted notifications: " + accepted);
});

Status

getPermissionSubscriptionState

Function

Get the current notification and permission state. Returns a OSPermissionSubscriptionState type described below.

permissionStatus

OSPermissionState

Notification Permissions state

hasPrompted

Bool

false = Not prompted
true = Prompted

status (iOS only)

Integer

0 = Not Determined
1 = Denied
2 = Authorized

subscriptionStatus

OSSubscriptionState

Push and OneSignal subscription state

state (Android only)

Integer

1 = Authorized
2 = Denied

subscribed (Recommended)

Bool

true = subscribed
false = not subscribed

userSubscriptionSetting

Bool

Defaults: true
Reflects value of setSubscription

userId

String

The OneSignal Player ID

pushToken

String

Device Identifier from FCM/APNs

window.plugins.OneSignal.getPermissionSubscriptionState(function(status) {
  status.permissionStatus.hasPrompted; // Bool
  status.permissionStatus.status; // iOS only: Integer: 0 = Not Determined, 1 = Denied, 2 = Authorized
  status.permissionStatus.state; //Android only: Integer: 1 = Authorized, 2 = Denied

  status.subscriptionStatus.subscribed; // Bool
  status.subscriptionStatus.userSubscriptionSetting; // Bool
  status.subscriptionStatus.userId; // String: OneSignal Player ID
  status.subscriptionStatus.pushToken; // String: Device Identifier from FCM/APNs
});

addPermissionObserver

The passed in function will be fired when a notification permission setting changes.
This includes the following events:

  • Notification permission prompt shown
  • The user accepting or declining the permission prompt
  • Enabling/disabling notifications for your app in the device Settings after returning to your app.
window.plugins.OneSignal.addPermissionObserver(function(state) {
  console.log("Notification permission state changed: " + state.hasPrompted);
  console.log("Notification permission status: " + state.status);
});

addSubscriptionObserver

The passed in function will be fired when a notification subscription property changes.

This includes the following events:

  • Getting a push token from Apple / Google.
  • Getting a player / user id from OneSignal
  • OneSignal.setSubscription is called
  • User disables or enables notifications
window.plugins.OneSignal.addSubscriptionObserver(function (state) {
  if (!state.from.subscribed && state.to.subscribed) {
    console.log("Subscribed for OneSignal push notifications!")
    // get player ID
    state.to.userId
  }
  console.log("Push Subscription state changed: " + JSON.stringify(state));
});

Tags

getTags

Method

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

Parameter
Type
Description

tagsReceivedCallback

function

Passed in function which will receive one parameter containing JSON.

tagsReceivedCallback

Contents of tagsReceivedCallback

Parameter
Type
Description

tags

JSON

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

window.plugins.OneSignal.getTags(function(tags) {
  console.log('Tags Received: ' + JSON.stringify(tags));
});

sendTag

Method

Tag a user based on an app event of your choosing so later you can create segments in Segments to target these users. Use sendTags if you need to set more than one tag on a user at a time.

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 or deleteTags.

window.plugins.OneSignal.sendTag("key", "value");

sendTags

Method

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

Parameter
Type
Description

keyValues

JSONObject

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.

window.plugins.OneSignal.sendTags({key: "value", key2: "value2"});

deleteTag

Method

Deletes a single 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.

window.plugins.OneSignal.deleteTag("key");

deleteTags

Method

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

Parameter
Type
Description

keys

Array

Keys to remove.

window.plugins.OneSignal.deleteTags(["key1", "key2"]);

Data

promptLocation

Method - iOS, Android

Prompts the user for location permissions. This allows for geotagging so you can send notifications to users based on location.

window.plugins.OneSignal.promptLocation();
iOS INSTRUCTIONS

You must add CoreLocation.framework in your target's Linked Frameworks and Libraries.

You must add all of the following to your iOS plist settings:

NSLocationUsageDescription

NSLocationAlwaysUsageDescription - background updates (optional)

NSLocationWhenInUseUsageDescription

Android Instructions

You must add one of the following Android Permissions:

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>

setLocationShared

Disable or enable location collection (defaults to enabled if your app has location permission). If you want to disable OneSignal from collection location data, please make sure to call this method before your app calls init()

window.plugins.OneSignal.setLocationShared(false)

Sending Notifications

postNotification

Method

Allows you to send notifications from user to user or schedule ones in the future to be delivered to the current device.

Parameter
Type
Description

parameters

Object

Contains notification options, see Create Notification POST call for all options.

onSuccess

Function

(Optional) callback fires when the notification was created on OneSignal's server.

returnedJson (JSON) - response from OneSignal's server.

onFailure

Function

callback fires when the notification failed to create

returnedJson (JSON) - response from OneSignal's server.

window.plugins.OneSignal.getIds(function(ids) {
  var notificationObj = { contents: {en: "message body"},
                          include_player_ids: [ids.userId]};
  window.plugins.OneSignal.postNotification(notificationObj,
    function(successResponse) {
      console.log("Notification Post Success:", successResponse);
    },
    function (failedResponse) {
      console.log("Notification Post Failed: ", failedResponse);
      alert("Notification Post Failed:\n" + JSON.stringify(failedResponse));
    }
  );
});

clearOneSignalNotifications

Method

Clears all notifications in the Notification Center aka Shade sent from OneSignal.

OneSignal.clearOneSignalNotifications();

setSubscription

Method

You can call this method with false to opt users out of receiving all notifications through OneSignal. You can pass true later to opt users back into notifications.

Parameter
Type

enable

Boolean

window.plugins.OneSignal.setSubscription(false);

Receiving Notifications

NotificationReceivedHandler

Handler

Only fires when a OneSignal notification is received if the app is in focus.

Parameter
Type
Description

notification

Contains both the user's response and properties of the notification.

Important behavior notes

  • If you will be displaying your own in app message when a notification is received make sure to call inFocusDisplaying with None to disable OneSignal's in app AlertBox.
window.plugins.OneSignal
  .startInit("YOUR_APP_ID")
  .handleNotificationReceived(function(jsonData) {
    alert("Notification received:\n" + JSON.stringify(jsonData));
    console.log('didReceiveRemoteNotificationCallBack: ' + JSON.stringify(jsonData));
  })
  .endInit();

The above example contains only a NotificationReceivedHandler that logs the notification to console. You will want to update it with the appropriate action, and you may wish to add other things to your init, such as a NotificationOpenedHandler (below) or other display options.

NotificationOpenedHandler

Handler

Use to process a OneSignal notification the user just tapped on.

Parameter
Type
Description

result

Contains both the user's response and properties of the notification.

window.plugins.OneSignal
  .startInit( "YOUR_APP_ID")
  .handleNotificationOpened(function(jsonData) {
    alert("Notification opened:\n" + JSON.stringify(jsonData));
    console.log('didOpenRemoteNotificationCallBack: ' + JSON.stringify(jsonData));   
  })
  .endInit();

OSNotificationOpenedResult

JSON Object

The information returned from a notification the user received.

Parameter
Type
Description

notification

Notification the user opened.

action

The action the user took on the notification.

OSNotification

JSON Object

The notification the user opened.

Parameter
Type
Description

isAppInFocus

Boolean

Was app in focus.

shown

Boolean

Was notification shown to the user. Will be false for silent notifications.

androidNotificationId

Integer

Android - Android Notification assigned to the notification. Can be used to cancel or replace the notification.

payload

Payload received from OneSignal.

displayType

How the notification was displayed to the user. Can be set to Notification, InAppAlert, or None if it was not displayed.

groupedNotifications

Android - Notification is a summary notification for a group this will contain all notification payloads it was created from.

displayType

How the notification was displayed to the user. Part of OSNotification. See inFocusDisplaying for more information on how this is used.

Notification - native notification display.
InAppAlert (Default) - native alert dialog display.
None - notification is silent, or inFocusDisplaying is disabled.

OSNotificationAction

JSON Object

The action the user took on the notification.

Parameter
Type
Description

type

ActionType

Was the notification opened normally (Opened) or was a button pressed on the notification (ActionTaken).

actionID

String

If type == ActionTaken then this will contain the id of the button pressed.

OSNotificationPayload

JSON Object

Contents and settings of the notification the user received.

Parameter
Type
Description

notificationId

String

OneSignal notification UUID.

title

String

Title of the notification.

body

String

Body of the notification.

additionalData

JSONObject

Custom additional data that was sent with the notification. Set on the dashboard under Options > Additional Data or with the 'data' field on the REST API.

smallIcon

String

Android - Small icon resource name set on the notification.

largeIcon

String

Android - Large icon set on the notification.

bigPicture

String

Android - Big picture image set on the notification.

smallIconAccentColor

String

Android - Accent color shown around small notification icon on Android 5+ devices. ARGB format.

launchUrl

String

URL to open when opening the notification.

sound

String

Sound resource to play when the notification is shown.

ledColor

String

Android - Devices that have a notification LED will blink in this color. ARGB format.

lockScreenVisibility

Integer

Android - Privacy setting for how the notification should be shown on the lockscreen of Android 5+ devices.
1 = Public (fully visible)(default)
0 = Private (Contents are hidden)
-1 = Secret (not shown)

groupKey

String

Android - Notifications with this same key will be grouped together as a single summary notification.

groupMessage

String

Android - Summary text displayed in the summary notification.

actionButtons

List of action buttons on the notification.

fromProjectNumber

String

Android - The Google project number the notification was sent under.

backgroundImageLayout

Android - If a background image was set this object will be available.

rawPayload

String

Raw JSON payload string received from OneSignal.

ActionButton

JSON Object

List of action buttons on the notification. Part of OSNotificationPayload.

Parameter
Type
Description

id

String

Id assigned to the button.

text

String

Text show on the button to the user.

icon

String

Android - Icon shown on the button.

BackgroundImageLayout

JSON Object - Android - Coming Soon

If a background image was set, this object will be available. Part of OSNotificationPayload.

Parameter
Type
Description

image

String

Image URL or name used as the background image.

titleTextColor

String

Text color of the title on the notification. ARGB Format.

bodyTextColor

String

Text color of the body on the notification. ARGB Format.

Email

setEmail

Method

setEmail allows you to set the user's email address with the OneSignal SDK. We offer several overloaded versions of this method.

window.plugins.OneSignal.setEmail("example@domain.com");

If you have a backend server, we strongly recommend using Identity Verification with your users. Your backend can generate an email authentication token and send it to your app. The following code also includes callbacks:

let emailAuthToken = ""; //from your backend server

window.plugins.OneSignal.setEmail("example@domain.com", emailAuthToken, function() {
    //Successfully set email

}, function(error) {
    //encountered an error setting email
    
});

logoutEmail

Method

If your app implements logout functionality, you can call logoutEmail to dissociate the email from the device:

window.plugins.OneSignal.logoutEmail(function(successResponse) {
    //Successfully logged out of email
}, function(error) {
    //Failed to log out of email
});

addEmailSubscriptionObserver

Method

We have also added a new email subscription observer to track changes to email subscriptions (ie. the user sets their email or logs out). In order to subscribe to email subscription changes you can implement the following:

window.plugins.OneSignal.addEmailSubscriptionObserver(function(stateChanges) {
    //Email subscription state changed
    let newEmailAddress = stateChanges.to.emailAddress;
    let newUserId = stateChanges.to.emailUserId;
});

Appearance

enableVibrate

Method - Android

By default OneSignal always vibrates the device when a notification is displayed unless the device is in a total silent mode. Passing false means that the device will only vibrate lightly when the device is in it's vibrate only mode.

You can link this action to a UI button to give your user a vibration option for your notifications.

Parameter
Type
Description

enable

Boolean

false to disable vibrate, true to re-enable it.

window.plugins.OneSignal.enableVibrate(false);

enableSound

Method - Android

By default OneSignal plays the system's default notification sound when the device's notification system volume is turned on. You may also set custom sounds on notifications. Passing false means that the device will only vibrate unless the device is set to a total silent mode.

You can link this action to a UI button to give your user a different sound option for your notifications.

Parameter
Type
Description

enable

Boolean

false to disable sound, true to re-enable it.

window.plugins.OneSignal.enableSound(false);

Debug

setLogLevel

Method

Enable logging to help debug if you run into an issue setting up OneSignal. The logging levels are available with increasingly more information, as follows:
0 = None
1 = Fatal
2 = Errors
3 = Warnings
4 = Info
5 = Debug
6 = Verbose

Parameters
Type
Description

logLevel

Integer

Sets the logging level to print to the iOS Xcode log or the Android LogCat log.

visualLevel

Integer

Sets the logging level to show as alert dialogs.

// Will show popup dialogs when the devices registers with Apple/Google and with OneSignal.
// Errors will be shown as popups too if there are any issues.
window.plugins.OneSignal.setLogLevel({logLevel: 4, visualLevel: 4});

Checkout our Github Cordova Example

Cordova SDK

OneSignal Cordova SDK Reference. Works with iOS, Android (and derivatives like Amazon) and Windows Phone 8.1.

For Developers