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

React Native SDK

OneSignal React Native SDK. Works with iOS and Android.

For Developers

Just starting with React Native?

Initialization

init

Method

Initializes the SDK. Accepts an app id and optional initialization parameters for arguments.

OneSignal.init("ce8572ae-ff57-4e77-a265-5c91f00ecc4c");

iOS Initialization Parameters

These settings are passed to the iOS SDK at initialization, such as:

OneSignal.init(appId, {kOSSettingsKeyAutoPrompt : true});

At the present time, none of these settings are available in the Android SDK.

Settings Key
Data Type
Description

kOSSettingsKeyAutoPrompt

Boolean

Determines if the application automatically prompts the user for permission to send push notification the first time the application opens.

kOSSettingsKeyInAppLaunchURL

Boolean

Determines if the application opens push notification URL's in an in-app web browser view, or exits the app and opens the URL in Safari

kOSSSettingsKeyPromptBeforeOpeningPushURL

Boolean

Determines if the app will pop up an alert view to ask the user if they want to open a URL. If this setting is false, the application will immediately open the web browser when the user taps a notification with a launch URL

kOSSettingsKeyInFocusDisplayOption

Integer

Determines how the app will display push notifications.

0 = None: When your app is open, OneSignal will not display a notification (it will be up to your app to provide a custom UI to display it)

1 = In App Alert: Notifications will display as a popup

2 = Notification: Notifications will display as normal notifications.

Events & Listeners

The OneSignal SDK emits various "events" such as the receipt of a notification or a click event. You can use the following methods to attach and remove callbacks to these events.

addEventListener

Method

Use this method to add a callback to an event.

removeEventListener

Method

Use this method to remove a callback from an event.

OneSignal.addEventListener('received', this.onReceived); // where onReceived is a callback
OneSignal.removeEventListener('received', this.onReceived); 

Events

Event String
Description

"received"

Fires when a notification is received

"opened"

Fires when a notification is opened (tapped)

"ids"

Fires when ids are available

"inAppMessageClicked"

Fires when In-App message action

Handling Notifications

Opened and Received Events

When any notification is opened or received the opened and received are activated and calling their callback functions defined in the listeners, passing an OSNotificationOpenResult or an OSNotification object encapsulating the event data.

componentWillMount() {
    OneSignal.addEventListener('received', this.onReceived);
    OneSignal.addEventListener('opened', this.onOpened);
}

onReceived(notification) {
    console.log("Notification received: ", notification);
}

onOpened(openResult) {
    console.log('Message: ', openResult.notification.payload.body);
    console.log('Data: ', openResult.notification.payload.additionalData);
    console.log('isActive: ', openResult.notification.isAppInFocus);
}

OSNotification object received example:

{
    shown: true, // BOOLEAN: If the notification was displayed to the user or not
    payload: {notificationID : "", contentAvailable : false, badge : 1, sound : "default", title : "Hello!", body : "World", launchURL : "", }, // OBJECT; the push data
    displayType: 1 //The display method of a received notification
}

Sending and Getting OneSignal Tags

We exposed the tags API of OneSignal to allow you to target users with notification later.

// Sending single tag
OneSignal.sendTag("key", "value");

// Sending multiple tags
OneSignal.sendTags({key: "value", key2: "value2"});

// Getting the tags from the server and use the received object
OneSignal.getTags((receivedTags) => {
    console.log(receivedTags);
});

// Delete a tag
OneSignal.deleteTag("key");

In-App Messaging

Check out In-App Messaging Quickstart to get an overview before diving into the SDK methods below.

Triggers

Triggers are something you fire in your app based on events/state changes which may show an In-App Message. Every time you add or remove a trigger with the below methods the SDK will evaluate if an In-App Message should be shown based on the Trigger conditions set on it via OneSignal Dashboard when it was created.

Triggers are reset each time your app is closed so make sure to set them again when starting your app if you need any of them to be persistent.

addTrigger

Method

Add a trigger, may show an In-App Message if its triggers conditions were met.

Parameter
Type
Description

key

string

Key for the trigger

value

string or number

Value for the trigger

OneSignal.addTrigger("level", 5);

addTriggers

Method

Add a key-value Object of triggers, may show an In-App Message if its triggers conditions were met.

Parameter
Type
Description

triggers

Object

Allows you to set multiple trigger key/value pairs simultaneously

OneSignal.addTriggers({"isAggie":"true", "clicked":"true"});

removeTriggerForKey

Method

Removes a single trigger for the given key, may show an In-App Message if its triggers conditions were met.

Parameter
Type
Description

key

string

Key for trigger to remove

OneSignal.removeTriggerForKey("isAggie");

removeTriggersForKeys

Method

Removes a list of triggers based on a collection of keys, may show an In-App Message if its triggers conditions were met.

Parameter
Type
Description

keys

array

Removes a collection of triggers from their keys

OneSignal.removeTriggersForKeys(["isAggie", "isCorps"]);

getTriggerValueForKey

Method

Gets a trigger value for a provided trigger key.

Parameter
Type
Description

key

string or number

Returns a single trigger value for the given key,
if it exists, otherwise returns null

OneSignal.getTriggerValueForKey("isAggie", function (value) {
  console.log("isAggie:", value)
});

In-App - Misc

pauseInAppMessages

Method

Allows you to temporarily pause all In-App Messages. You may want to do this while the user is watching a video playing a match in your game to make sure they don't get interrupted at a bad time.

Parameter
Type
Description

pause

boolean

To pause set true
To resume set false

OneSignal.pauseInAppMessages(true);

In-App Message Click Handler

Use the "inAppMessageClicked" event to add an In-App Message clicked handler. The instance will be called when an In-App Message action is tapped on.

Example

componentWillMount() {
    OneSignal.addEventListener('inAppMessageClicked', this.onInAppClicked);
}

componentWillUnmount() {
    OneSignal.removeEventListener('inAppMessageClicked', this.onInAppClicked);
}

onInAppClicked(action) {
   let {clickUrl, clickName, firstClick, closesMessage} = action;
   // ...
}

Action Object
An in-app message action object is passed into the handler automatically

Field
Type
Description

first_click

boolean

true if this is the first time the user has pressed
any action on the In App Message.

closes_message

boolean

Did the action close the In App Message.
true the In App Message will animate off the screen.
false the In App Message will stay on screen until the user dismisses.

click_url

string

An optional URL that opens when the action takes place. Only present if set through dashboard.

click_name

string

An optional click name defined for the action element. Only present if set through dashboard.

Email

setEmail

Method

OneSignal now allows you to send emails to your userbase. This email can be set using the OneSignal react-native SDK.

To set the email:

let emailAuthCode = ""; //Your email auth code should be securely generated by your backend server

OneSignal.setEmail("test@test.com", emailAuthCode, {(error) => {
    //handle error if it occurred
}});

If you don't want to implement email auth hashing on your backend (which is heavily recommended), you can still use the OneSignal email feature in an unauthenticated state like this:

OneSignal.setEmail("test@test.com", {(error) => {
    //handle error if it occurred
}});

logoutEmail

Method

If your application implements logout functionality, you can logout of the OneSignal email for this user using the logout function:

OneSignal.logoutEmail({(error) => {
    //handle error if it occurred
}});

Player & Device Info

Getting Player ID and Push Token

We exposed the idsAvailable API of OneSignal (both Android & iOS) as an event.
Listen for ids event and define a callback to handle the returned object.

componentWillMount() {
    OneSignal.init("YOUR_ONESIGNAL_APPID");

    OneSignal.addEventListener('ids', this.onIds);
}

componentWillUnmount() {
    OneSignal.removeEventListener('ids', this.onIds);
}

onIds(device) {
    console.log('Device info: ', device);
}

Behavior

Enable Vibration

We exposed the enableVibrate API of OneSignal (Android only).

You can call this from your UI from a button press for example to give your user's options for your notifications. 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.

// Setting enableVibrate
OneSignal.enableVibrate(true);

Enable Sound

We exposed the enableSound API of OneSignal (Android only).

You can call this from your UI from a button press for example to give your user's options for your notifications. By default OneSignal plays the system's default notification sound when the device's notification system volume is turned on. Passing false means that the device will only vibrate unless the device is set to a total silent mode.

// Setting enableSound
OneSignal.enableSound(true);

Set Alert Focus Behavior

We exposed the inFocusDisplaying API of OneSignal.

Both iOS and Android

  • 0 = None - Will not display a notification, instead only onReceived will fire where you can display your own in app messages.
  • 1 = InAppAlert - (Default) Will display an Android AlertDialog with the message contains.
  • 2 = Notification - Notification will display in the Notification Shade. Same as when the app is not in focus.
// Example, always display notification in shade.
OneSignal.inFocusDisplaying(2);

Subscription Status

Change User Subscription Status

Use this method only on subscribed users. It will not subscribe users that have turned off push in the App Settings or denied subscription through the native prompt on iOS.

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

You cannot resubscribe users that have opted out of push in any other way besides setting setSubscription(false);

// Setting setSubscription
OneSignal.setSubscription(true);

Check Push Notification and User Subscription Status

We exposed the getPermissionSubscriptionState API of OneSignal (both Android & iOS).

Allows you to check whether notifications are enabled for the app, whether user is subscribed to notifications through OneSignal, and what the user's in-app subscription preference is. It also provides access to pushToken and userId

// Check push notification and OneSignal subscription statuses
OneSignal.getPermissionSubscriptionState((status) => {
    console.log(status);
});

Other methods

Post Notification (Peer-to-Peer Notifications)

We exposed the postNotification API of OneSignal, currently supports one Player ID to send a notification to.
We call it internally P2P Notification, and therefore there is a special attribute to listen to while receiving the notification.

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

The OneSignal documentation shows how to pass the parameters as here:

// Calling postNotification

let otherParameters = {"ios_attachments" : {"image1" : "{image_url}"}};
let data = arr // some array as payload
let contents = {
	'en': 'You got notification from user'
}
OneSignal.postNotification(contents, data, playerId, otherParameters);

// Calling postNotification with external ids only

OneSignal.postNotification(contents, data, null, {include_external_user_ids:[<external_id>, <external_id>, <external_id>]});


// Listening to postNotification using OneSignal.Configure:
onNotificationOpened: function(message, data, isActive) {
	if (data.p2p_notification) {
		for (var num in data.p2p_notification) {
			// console.log(data.p2p_notification[num]);
		}
	}
}

Prompt Location

We exposed the promptLocation API of OneSignal.

// Calling promptLocation
OneSignal.promptLocation();

Android
In your AndroidManifest.xml, add the following location permissions:


<!-- Optional - Add the necessary permissions (Choose one of those) -->

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/> <!-- Approximate location - If you want to use promptLocation for letting OneSignal know the user location. -->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/> <!--  Precise location If you want to use promptLocation for letting OneSignal know the user location. -->

<!-- End optional permissions -->

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

iOS
For iOS, make sure you set the NSLocationWhenInUseUsageDescription or the NSLocationAlwaysUsageDescription in your info.plist. (Location Always also requires the location background mode capability)

setLocationShared

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

OneSignal.setLocationShared(false);

Clear Notifications (Android Only)

We exposed the clearOneSignalNotifications API of OneSignal (currently supported only on Android).

Removes all OneSignal notifications from the Notification Shade.

// Calling clearOneSignalNotifications
OneSignal.clearOneSignalNotifications();

Cancel Notifications (Android Only)

We exposed the cancelNotification API of OneSignal (currently supported only on Android).

Cancels a single OneSignal notification based on its Android notification integer id. You can get the notification Id when invoking OneSignal.onNotificationOpened while receiving a notification.

// Calling cancelNotification
OneSignal.cancelNotification(id);

Check Push Notification Permissions (iOS Only)

See what push permissions are currently enabled. callback will be invoked with a permissions object (currently supported only on iOS).

// Requesting permissions
OneSignal.checkPermissions((permissions) => {
	console.log(permissions);
});

Request Push Notification Permissions (iOS Only)

We exposed the requestPermissions method (currently supported only on iOS).

// Setting requestPermissions
permissions = {
    alert: true,
    badge: true,
    sound: true
};
OneSignal.requestPermissions(permissions);

Register For Push Notifications (iOS Only)

We exposed the registerForPushNotifications API of OneSignal (currently supported only on iOS).

*Call when you want to prompt the user to accept push notifications. Only call once and only if you passed @NO to kOSSettingsKeyAutoPrompt on init.

// Calling registerForPushNotifications
OneSignal.registerForPushNotifications();

Register For Push Notifications with Callback (iOS Only)

*Call when you want to prompt the user to accept push notifications. Only call once and only if you passed @NO to kOSSettingsKeyAutoPrompt on init.

Accepts a callback that will execute after the user makes the permission choice. The parameter passed to the callback is a boolean value of the permission.

// Calling registerForPushNotifications
OneSignal.promptForPushNotificationsWithUserResponse(myCallback);

function myCallback(permission){
	// do something with permission value
}

GDPR Consent Functions

setRequiresUserPrivacyConsent

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.

componentWillMount() {
  // Will delay initialization of the SDK until the user provides consent
  OneSignal.setRequiresUserPrivacyConsent(true);
  OneSignal.init("YOUR_ONESIGNAL_APPID");
}

provideUserConsent

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
  OneSignal.provideUserConsent(true);
}

External User ID's

setExternalUserId

If your system assigns unique identifiers to users, it can be annoying to have to also remember their OneSignal user ID's as well. To make things easier, OneSignal now allows you to set an external_id for your users. Simply call this method, pass in your custom user ID (as a string), and from now on when you send a push notification, you can use include_external_user_ids instead of include_player_ids.

let myCustomUniqueUserId = "something from my backend server";

OneSignal.setExternalUserId(myCustomUniqueUserId);

removeExternalUserId

If your user logs out of your app and you would like to disassociate their custom user ID from your system with their OneSignal user ID, you will want to call this method.


//usually called after the user logs out of your app
OneSignal.removeExternalUserId()

Debugging

setLogLevel

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.

OneSignal.setLogLevel(6, 0);

React Native SDK


OneSignal React Native SDK. Works with iOS and Android.

For Developers

Suggested Edits are limited on API Reference Pages

You can only suggest edits to Markdown body content, but not to the API spec.