Need help upgrading to Ionic Framework 4.0? Get assistance with our Enterprise Migration Services EXPLORE NOW

OneSignal

Improve this doc

The OneSignal plugin is an client implementation for using the OneSignal Service. OneSignal is a simple implementation for delivering push notifications.

Please view the official OneSignal Ionic SDK Installation guide for more information.

Icons

If you want to use generated icons with command ionic cordova resources:

  1. Add a file to your hooks directory called copy_android_notification_icons.js

  2. Configure the hook in your config.xml

    <platform name="android">
        <hook type="after_prepare" src="hooks/copy_android_notification_icons.js" />
    </platform>
    
  3. Put the following code in it:

#!/usr/bin/env node

var fs = require('fs');
var path = require('path');

var filestocopy = [{
    "resources/android/icon/drawable-hdpi-icon.png":
        "platforms/android/app/src/main/res/drawable-hdpi/ic_stat_onesignal_default.png"
}, {
    "resources/android/icon/drawable-mdpi-icon.png":
        "platforms/android/app/src/main/res/drawable-mdpi/ic_stat_onesignal_default.png"
}, {
    "resources/android/icon/drawable-xhdpi-icon.png":
        "platforms/android/app/src/main/res/drawable-xhdpi/ic_stat_onesignal_default.png"
}, {
    "resources/android/icon/drawable-xxhdpi-icon.png":
        "platforms/android/app/src/main/res/drawable-xxhdpi/ic_stat_onesignal_default.png"
}, {
    "resources/android/icon/drawable-xxxhdpi-icon.png":
        "platforms/android/app/src/main/res/drawable-xxxhdpi/ic_stat_onesignal_default.png"
} ];

module.exports = function(context) {

    // no need to configure below
    var rootdir = context.opts.projectRoot;

    filestocopy.forEach(function(obj) {
        Object.keys(obj).forEach(function(key) {
            var val = obj[key];
            var srcfile = path.join(rootdir, key);
            var destfile = path.join(rootdir, val);
            console.log("copying "+srcfile+" to "+destfile);
            var destdir = path.dirname(destfile);
            if (fs.existsSync(srcfile) && fs.existsSync(destdir)) {
                fs.createReadStream(srcfile).pipe(
                    fs.createWriteStream(destfile));
            }
        });
    });

};
  1. From the root of your project make the file executable: $ chmod +x hooks/copy_android_notification_icons.js

Repo: https://github.com/OneSignal/OneSignal-Cordova-SDK

Installation

  1. Install the Cordova and Ionic Native plugins:
    $ ionic cordova plugin add onesignal-cordova-plugin
    $ npm install --save @ionic-native/onesignal@4
    
  2. Add this plugin to your app's module

Supported platforms

Usage

import { OneSignal } from '@ionic-native/onesignal';

constructor(private oneSignal: OneSignal) { }

...

this.oneSignal.startInit('b2f7f966-d8cc-11e4-bed1-df8f05be55ba', '703322744261');

this.oneSignal.inFocusDisplaying(this.oneSignal.OSInFocusDisplayOption.InAppAlert);

this.oneSignal.handleNotificationReceived().subscribe(() => {
 // do something when notification is received
});

this.oneSignal.handleNotificationOpened().subscribe(() => {
  // do something when a notification is opened
});

this.oneSignal.endInit();

Instance Members

startInit(appId, googleProjectNumber)

Start the initialization process. Once you are done configuring OneSignal, call the endInit function.

Param Type Details
appId string

Your OneSignal app id

googleProjectNumber string

ANDROID - your Google project number; only required for Android GCM/FCM pushes.

Returns: any

handleNotificationReceived()

Callback to run when a notification is received, whether it was displayed or not.

Returns: Observable<OneSignalReceivedNotification>

handleNotificationOpened()

Callback to run 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).

Returns: Observable<OneSignalOpenedNotification>

iOSSettings(settings)

Platforms:iOS 

iOS - Settings for iOS apps

Param Type Details
settings

kOSSettingsKeyAutoPrompt: boolean = true Auto prompt user for notification permissions.

kOSSettingsKeyInAppLaunchURL: boolean = false Launch notifications with a launch URL as an in app webview.

Returns: any

endInit()

Must be called after startInit to complete initialization of OneSignal.

Returns: any

promptForPushNotificationsWithUserResponse()

Platforms:iOS 

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

Returns: Promise<boolean>

getTags()

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

Quirk: You must wait for getTags to resolve before calling it again, as the plugin will only process the last method call and discard any previous ones.

Returns: Promise<any> Returns a Promise that resolves when tags are recieved.

getIds()

Lets you retrieve the OneSignal user id and device token. Your handler is called after the device is successfully registered with OneSignal.

Returns: Promise<Object> Returns a Promise that resolves if the device was successfully registered.

userId {string} OneSignal userId is a UUID formatted string. (unique per device per app)

pushToken {string} A push token is a Google/Apple assigned identifier(unique per device per app).

sendTag(Key, Value)

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

Param Type Details
Key string

of your choosing to create or update.

Value string

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

sendTags(Pass)

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

Param Type Details
Pass string

a json object with key/value pairs like: {key: "value", key2: "value2"}

deleteTag(Key)

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

Param Type Details
Key string

to remove.

deleteTags(Keys)

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

Param Type Details
Keys Array<string>

to remove.

registerForPushNotifications()

Call this when you would like to prompt an iOS user to accept push notifications with the default system prompt. Only works if you set kOSSettingsAutoPrompt to false in iOSSettings

enableVibrate(false)

Warning: Only applies to Android and Amazon. 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.

Param Type Details
false boolean

to disable vibrate, true to re-enable it.

enableSound(false)

Warning: Only applies to Android and Amazon. 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.

Param Type Details
false boolean

to disable sound, true to re-enable it.

inFocusDisplaying(displayOption)

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.

Param Type Details
displayOption DisplayType

Returns: any

setSubscription(enable)

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.

Param Type Details
enable boolean

getPermissionSubscriptionState()

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

Returns: Promise<OSPermissionSubscriptionState>

postNotification(Parameters)

Param Type Details
Parameters notificationObj

see POST documentation

Returns: Promise<any> Returns a Promise that resolves if the notification was send successfully.

cancelNotification(notificationId)

Cancels a single OneSignal notification based on its Android notification integer id. Use instead of NotificationManager.cancel(id); otherwise the notification will be restored when your app is restarted.

Param Type Details
notificationId string

promptLocation()

Prompts the user for location permission to allow geotagging based on the “Location radius” filter on the OneSignal dashboard.

syncHashedEmail(email)

Param Type Details
email string

setLogLevel(contains)

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

The higher the value the more information is shown.

Param Type Details
contains loglevel

two properties: logLevel (for console logging) and visualLevel (for dialog messages)

setLocationShared(shared)

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

Param Type Details
shared boolean

addPermissionObserver()

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

Returns: Observable<any>

addSubscriptionObserver()

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

Returns: Observable<any>

setEmail(email, emailAuthToken)

Allows you to set the user’s email address with the OneSignal SDK.

Param Type Details
email string

Email address

emailAuthToken string

Email auth tokenOptional

logoutEmail()

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

addEmailSubscriptionObserver()

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

Returns: Observable<any>

clearOneSignalNotifications()

Clears all OneSignal notifications

setRequiresUserPrivacyConsent(required)

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.

Param Type Details
required boolean

provideUserConsent(granted)

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.

Param Type Details
granted boolean

userProvidedPrivacyConsent(callback)

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

Param Type Details
callback Function

OSNotification

Param Type Details
isAppInFocus boolean

Was app in focus.

(optional)
shown boolean

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

(optional)
androidNotificationId number

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

(optional)
payload OSNotificationPayload

Payload received from OneSignal.

(optional)
displayType OSDisplayType

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

(optional)
groupedNotifications OSNotificationPayload[]

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

(optional)
app_id string (optional)
contents any (optional)
headings any (optional)
isIos boolean (optional)
isAndroid boolean (optional)
isWP boolean (optional)
isWP_WNS boolean (optional)
isAdm boolean (optional)
isChrome boolean (optional)
isChromeWeb boolean (optional)
isSafari boolean (optional)
isAnyWeb boolean (optional)
included_segments string[] (optional)
excluded_segments string[] (optional)
include_player_ids string[] (optional)
include_ios_tokens string[] (optional)
include_android_reg_ids string[] (optional)
include_wp_uris string[] (optional)
include_wp_wns_uris string[] (optional)
include_amazon_reg_ids string[] (optional)
include_chrome_reg_ids string[] (optional)
include_chrome_web_reg_ids string[] (optional)
app_ids string[] (optional)
tags any[] (optional)
ios_badgeType string (optional)
ios_badgeCount number (optional)
ios_sound string (optional)
android_sound string (optional)
adm_sound string (optional)
wp_sound string (optional)
wp_wns_sound string (optional)
data any (optional)
buttons any (optional)
collapse_id string (optional)
small_icon string (optional)
large_icon string (optional)
big_picture string (optional)
adm_small_icon string (optional)
adm_large_icon string (optional)
adm_big_picture string (optional)
chrome_icon string (optional)
chrome_big_picture string (optional)
chrome_web_icon string (optional)
firefox_icon string (optional)
url string (optional)
send_after string (optional)
delayed_option string (optional)
delivery_time_of_day string (optional)
android_led_color string (optional)
android_accent_color string (optional)
android_visibility number (optional)
content_available boolean (optional)
amazon_background_data boolean (optional)
template_id string (optional)
android_group string (optional)
android_group_message any (optional)
adm_group string (optional)
adm_group_message any (optional)
ttl number (optional)
priority number (optional)
ios_category string (optional)

OSLockScreenVisibility

Param Type Details
Public 1

Fully visible (default)

Private 0

Contents are hidden

Secret -1

Not shown

OSDisplayType

Param Type Details
None 0

notification is silent, or inFocusDisplaying is disabled.

InAppAlert 1

(DEFAULT) - native alert dialog display.

Notification 2

native notification display.

OSNotificationPayload

Param Type Details
notificationID string

OneSignal notification UUID.

title string

Title of the notification.

body string

Body of the notification.

additionalData any

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.

(optional)
smallIcon string

ANDROID - Small icon resource name set on the notification.

(optional)
largeIcon string

ANDROID - Large icon set on the notification.

(optional)
bigPicture string

ANDROID - Big picture image set on the notification.

(optional)
smallIconAccentColor string

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

(optional)
launchURL string

URL to open when opening the notification.

(optional)
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.

(optional)
lockScreenVisibility OSLockScreenVisibility (optional)
groupKey string

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

(optional)
groupMessage string

ANDROID - Summary text displayed in the summary notification.

(optional)
actionButtons OSActionButton[]

List of action buttons on the notification.

fromProjectNumber string

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

(optional)
backgroundImageLayout OSBackgroundImageLayout

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

(optional)
priority number (optional)
rawPayload string

List of action buttons on the notification.

OSActionButton

Param Type Details
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.

OSBackgroundImageLayout

Param Type Details
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.

OSNotificationOpenedResult

Param Type Details
action */ actionID?: string; }
notification OSNotification

OSActionType

Param Type Details
Opened 0
ActionTake 1

API

Native

General