Skip to content

jokio/capacitor-native-onesignal

Repository files navigation

capacitor-native-onesignal

OneSignal push notification and in-app messaging plugin for Capacitor v8+.

This plugin integrates OneSignal SDK v5.x for iOS and Android with Capacitor v8+ applications.

Features

  • Push notifications with rich content support
  • In-app messaging
  • User segmentation with tags and aliases
  • Email and SMS subscriptions
  • Live Activities support (iOS 16.1+)
  • Location-based targeting
  • Privacy/consent management

Install

npm install capacitor-native-onesignal
npx cap sync

iOS Setup

Add the following to your ios/App/App/AppDelegate.swift:

import OneSignalFramework

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    // OneSignal is initialized via the Capacitor plugin
    return true
}

Enable Push Notifications capability in Xcode:

  1. Select your project target
  2. Go to "Signing & Capabilities"
  3. Add "Push Notifications" capability
  4. Add "Background Modes" capability and enable "Remote notifications"

Android Setup

No additional setup required. The plugin automatically configures the OneSignal SDK.

For Firebase Cloud Messaging, ensure you have:

  1. Added google-services.json to android/app/
  2. Applied the Google Services plugin in your android/app/build.gradle

Usage

Initialize OneSignal

import { OneSignal } from 'capacitor-native-onesignal';

// Initialize with your OneSignal App ID
await OneSignal.initialize({ appId: 'YOUR_ONESIGNAL_APP_ID' });

Request Notification Permission

const { permission } = await OneSignal.requestPermission({ fallbackToSettings: true });
console.log('Permission granted:', permission);

Login/Logout Users

// Login a user
await OneSignal.login({ externalId: 'user-123' });

// Logout user
await OneSignal.logout();

Tags

// Add a single tag
await OneSignal.addTag({ key: 'level', value: '5' });

// Add multiple tags
await OneSignal.addTags({ tags: { level: '5', score: '1000' } });

// Get tags
const { tags } = await OneSignal.getTags();
console.log('Tags:', tags);

// Remove tags
await OneSignal.removeTags({ keys: ['level', 'score'] });

Listen for Notifications

// Notification clicked
OneSignal.addListener('notificationClicked', (event) => {
  console.log('Notification clicked:', event.notification);
  console.log('Action:', event.result);
});

// Notification will display in foreground
OneSignal.addListener('notificationWillDisplay', (event) => {
  console.log('Notification will display:', event.notification);
});

// Permission changed
OneSignal.addListener('permissionChanged', (event) => {
  console.log('Permission changed:', event.permission);
});

In-App Messages

// Add triggers for in-app messages
await OneSignal.addTrigger({ key: 'screen', value: 'home' });

// Pause in-app messages
await OneSignal.setInAppMessagesPaused({ paused: true });

// Listen for in-app message clicks
OneSignal.addListener('inAppMessageClicked', (event) => {
  console.log('In-app message clicked:', event.message);
});

Push Subscription

// Opt in/out of push notifications
await OneSignal.optIn();
await OneSignal.optOut();

// Get subscription info
const { subscriptionId } = await OneSignal.getPushSubscriptionId();
const { token } = await OneSignal.getPushSubscriptionToken();
const { optedIn } = await OneSignal.getOptedIn();

API

initialize(...)

initialize(options: { appId: string; }) => Promise<void>

Initialize the OneSignal SDK with your app ID. Must be called before any other OneSignal methods.

Param Type Description
options { appId: string; } - The initialization options containing the appId

login(...)

login(options: { externalId: string; }) => Promise<void>

Login a user with their external user ID. This will associate the current device with the user.

Param Type Description
options { externalId: string; } - The login options containing the externalId

logout()

logout() => Promise<void>

Logout the current user. This will disassociate the current device from the user.


setConsentRequired(...)

setConsentRequired(options: { required: boolean; }) => Promise<void>

Set whether user consent is required before data is sent to OneSignal. Must be called before initialize() if you require consent.

Param Type Description
options { required: boolean; } - Whether consent is required

setConsentGiven(...)

setConsentGiven(options: { given: boolean; }) => Promise<void>

Set whether the user has given consent for data collection.

Param Type Description
options { given: boolean; } - Whether consent is given

setLogLevel(...)

setLogLevel(options: { logLevel: LogLevel; }) => Promise<void>

Set the log level for the OneSignal SDK.

Param Type Description
options { logLevel: LogLevel; } - The log level to set

setAlertLevel(...)

setAlertLevel(options: { logLevel: LogLevel; }) => Promise<void>

Set the visual log level (shows alerts for logs at or above this level).

Param Type Description
options { logLevel: LogLevel; } - The alert level to set

addTag(...)

addTag(options: { key: string; value: string; }) => Promise<void>

Add a single tag to the current user.

Param Type Description
options { key: string; value: string; } - The key and value of the tag

addTags(...)

addTags(options: { tags: Record<string, string>; }) => Promise<void>

Add multiple tags to the current user.

Param Type Description
options { tags: Record<string, string>; } - The tags to add

removeTag(...)

removeTag(options: { key: string; }) => Promise<void>

Remove a tag from the current user.

Param Type Description
options { key: string; } - The key of the tag to remove

removeTags(...)

removeTags(options: { keys: string[]; }) => Promise<void>

Remove multiple tags from the current user.

Param Type Description
options { keys: string[]; } - The keys of the tags to remove

getTags()

getTags() => Promise<{ tags: Record<string, string>; }>

Get the tags for the current user.

Returns: Promise<{ tags: Record<string, string>; }>


addAlias(...)

addAlias(options: { label: string; id: string; }) => Promise<void>

Add an alias for the current user.

Param Type Description
options { label: string; id: string; } - The alias label and ID

addAliases(...)

addAliases(options: { aliases: Record<string, string>; }) => Promise<void>

Add multiple aliases for the current user.

Param Type Description
options { aliases: Record<string, string>; } - The aliases to add

removeAlias(...)

removeAlias(options: { label: string; }) => Promise<void>

Remove an alias from the current user.

Param Type Description
options { label: string; } - The alias label to remove

removeAliases(...)

removeAliases(options: { labels: string[]; }) => Promise<void>

Remove multiple aliases from the current user.

Param Type Description
options { labels: string[]; } - The alias labels to remove

addEmail(...)

addEmail(options: { email: string; }) => Promise<void>

Add an email address to the current user.

Param Type Description
options { email: string; } - The email address to add

removeEmail(...)

removeEmail(options: { email: string; }) => Promise<void>

Remove an email address from the current user.

Param Type Description
options { email: string; } - The email address to remove

addSms(...)

addSms(options: { smsNumber: string; }) => Promise<void>

Add an SMS number to the current user.

Param Type Description
options { smsNumber: string; } - The SMS number to add

removeSms(...)

removeSms(options: { smsNumber: string; }) => Promise<void>

Remove an SMS number from the current user.

Param Type Description
options { smsNumber: string; } - The SMS number to remove

setLanguage(...)

setLanguage(options: { language: string; }) => Promise<void>

Set the language for the current user.

Param Type Description
options { language: string; } - The language code (e.g., "en", "es")

getOnesignalId()

getOnesignalId() => Promise<{ onesignalId: string | null; }>

Get the OneSignal ID for the current user.

Returns: Promise<{ onesignalId: string | null; }>


getExternalId()

getExternalId() => Promise<{ externalId: string | null; }>

Get the external ID for the current user.

Returns: Promise<{ externalId: string | null; }>


getPermission()

getPermission() => Promise<{ permission: boolean; }>

Check if push notification permission has been granted.

Returns: Promise<{ permission: boolean; }>


permissionNative()

permissionNative() => Promise<{ permission: OSNotificationPermission; }>

Get the native permission status.

Returns: Promise<{ permission: OSNotificationPermission; }>


requestPermission(...)

requestPermission(options?: { fallbackToSettings?: boolean | undefined; } | undefined) => Promise<{ permission: boolean; }>

Request push notification permission from the user.

Param Type Description
options { fallbackToSettings?: boolean; } - Optional settings for the permission request

Returns: Promise<{ permission: boolean; }>


canRequestPermission()

canRequestPermission() => Promise<{ canRequest: boolean; }>

Check if permission can be requested.

Returns: Promise<{ canRequest: boolean; }>


registerForProvisionalAuthorization()

registerForProvisionalAuthorization() => Promise<{ accepted: boolean; }>

Register for provisional authorization (iOS only). Allows sending notifications to the Notification Center without prompting.

Returns: Promise<{ accepted: boolean; }>


clearAllNotifications()

clearAllNotifications() => Promise<void>

Clear all notifications created by OneSignal.


removeNotification(...)

removeNotification(options: { notificationId: number; }) => Promise<void>

Remove a specific notification by its Android notification ID.

Param Type Description
options { notificationId: number; } - The notification ID to remove

removeGroupedNotifications(...)

removeGroupedNotifications(options: { groupKey: string; }) => Promise<void>

Remove all notifications in a group (Android only).

Param Type Description
options { groupKey: string; } - The group key to remove

getPushSubscriptionId()

getPushSubscriptionId() => Promise<{ subscriptionId: string | null; }>

Get the push subscription ID.

Returns: Promise<{ subscriptionId: string | null; }>


getPushSubscriptionToken()

getPushSubscriptionToken() => Promise<{ token: string | null; }>

Get the push subscription token.

Returns: Promise<{ token: string | null; }>


getOptedIn()

getOptedIn() => Promise<{ optedIn: boolean; }>

Check if the user is opted in to push notifications.

Returns: Promise<{ optedIn: boolean; }>


optIn()

optIn() => Promise<void>

Opt the user in to push notifications.


optOut()

optOut() => Promise<void>

Opt the user out of push notifications.


addTrigger(...)

addTrigger(options: { key: string; value: string; }) => Promise<void>

Add a trigger for in-app messages.

Param Type Description
options { key: string; value: string; } - The trigger key and value

addTriggers(...)

addTriggers(options: { triggers: Record<string, string>; }) => Promise<void>

Add multiple triggers for in-app messages.

Param Type Description
options { triggers: Record<string, string>; } - The triggers to add

removeTrigger(...)

removeTrigger(options: { key: string; }) => Promise<void>

Remove a trigger for in-app messages.

Param Type Description
options { key: string; } - The trigger key to remove

removeTriggers(...)

removeTriggers(options: { keys: string[]; }) => Promise<void>

Remove multiple triggers for in-app messages.

Param Type Description
options { keys: string[]; } - The trigger keys to remove

clearTriggers()

clearTriggers() => Promise<void>

Clear all triggers for in-app messages.


setInAppMessagesPaused(...)

setInAppMessagesPaused(options: { paused: boolean; }) => Promise<void>

Pause or resume in-app messages.

Param Type Description
options { paused: boolean; } - Whether to pause in-app messages

getInAppMessagesPaused()

getInAppMessagesPaused() => Promise<{ paused: boolean; }>

Check if in-app messages are paused.

Returns: Promise<{ paused: boolean; }>


setLocationShared(...)

setLocationShared(options: { shared: boolean; }) => Promise<void>

Set whether location sharing is enabled.

Param Type Description
options { shared: boolean; } - Whether location sharing is enabled

getLocationShared()

getLocationShared() => Promise<{ shared: boolean; }>

Check if location sharing is enabled.

Returns: Promise<{ shared: boolean; }>


requestLocationPermission()

requestLocationPermission() => Promise<void>

Request location permission from the user.


enterLiveActivity(...)

enterLiveActivity(options: { activityId: string; token: string; }) => Promise<void>

Enter a live activity (iOS 16.1+ only).

Param Type Description
options { activityId: string; token: string; } - The activity ID and token

exitLiveActivity(...)

exitLiveActivity(options: { activityId: string; }) => Promise<void>

Exit a live activity (iOS 16.1+ only).

Param Type Description
options { activityId: string; } - The activity ID

setPushToStartToken(...)

setPushToStartToken(options: { activityType: string; token: string; }) => Promise<void>

Set the push-to-start token for a live activity type (iOS 17.2+ only).

Param Type Description
options { activityType: string; token: string; } - The activity type and token

removePushToStartToken(...)

removePushToStartToken(options: { activityType: string; }) => Promise<void>

Remove the push-to-start token for a live activity type (iOS 17.2+ only).

Param Type Description
options { activityType: string; } - The activity type

addListener('notificationClicked', ...)

addListener(eventName: 'notificationClicked', listenerFunc: (event: NotificationClickEvent) => void) => Promise<PluginListenerHandle>

Listen for notification click events.

Param Type
eventName 'notificationClicked'
listenerFunc (event: NotificationClickEvent) => void

Returns: Promise<PluginListenerHandle>


addListener('notificationWillDisplay', ...)

addListener(eventName: 'notificationWillDisplay', listenerFunc: (event: NotificationWillDisplayEvent) => void) => Promise<PluginListenerHandle>

Listen for notification foreground will display events. Call event.notification.display() to display the notification.

Param Type
eventName 'notificationWillDisplay'
listenerFunc (event: NotificationWillDisplayEvent) => void

Returns: Promise<PluginListenerHandle>


addListener('permissionChanged', ...)

addListener(eventName: 'permissionChanged', listenerFunc: (event: PermissionChangedState) => void) => Promise<PluginListenerHandle>

Listen for permission changes.

Param Type
eventName 'permissionChanged'
listenerFunc (event: PermissionChangedState) => void

Returns: Promise<PluginListenerHandle>


addListener('pushSubscriptionChanged', ...)

addListener(eventName: 'pushSubscriptionChanged', listenerFunc: (event: PushSubscriptionChangedState) => void) => Promise<PluginListenerHandle>

Listen for push subscription changes.

Param Type
eventName 'pushSubscriptionChanged'
listenerFunc (event: PushSubscriptionChangedState) => void

Returns: Promise<PluginListenerHandle>


addListener('userChanged', ...)

addListener(eventName: 'userChanged', listenerFunc: (event: UserChangedState) => void) => Promise<PluginListenerHandle>

Listen for user state changes.

Param Type
eventName 'userChanged'
listenerFunc (event: UserChangedState) => void

Returns: Promise<PluginListenerHandle>


addListener('inAppMessageClicked', ...)

addListener(eventName: 'inAppMessageClicked', listenerFunc: (event: InAppMessageClickEvent) => void) => Promise<PluginListenerHandle>

Listen for in-app message click events.

Param Type
eventName 'inAppMessageClicked'
listenerFunc (event: InAppMessageClickEvent) => void

Returns: Promise<PluginListenerHandle>


addListener('inAppMessageWillDisplay', ...)

addListener(eventName: 'inAppMessageWillDisplay', listenerFunc: (event: InAppMessageWillDisplayEvent) => void) => Promise<PluginListenerHandle>

Listen for in-app message will display events.

Param Type
eventName 'inAppMessageWillDisplay'
listenerFunc (event: InAppMessageWillDisplayEvent) => void

Returns: Promise<PluginListenerHandle>


addListener('inAppMessageDidDisplay', ...)

addListener(eventName: 'inAppMessageDidDisplay', listenerFunc: (event: InAppMessageDidDisplayEvent) => void) => Promise<PluginListenerHandle>

Listen for in-app message did display events.

Param Type
eventName 'inAppMessageDidDisplay'
listenerFunc (event: InAppMessageDidDisplayEvent) => void

Returns: Promise<PluginListenerHandle>


addListener('inAppMessageWillDismiss', ...)

addListener(eventName: 'inAppMessageWillDismiss', listenerFunc: (event: InAppMessageWillDismissEvent) => void) => Promise<PluginListenerHandle>

Listen for in-app message will dismiss events.

Param Type
eventName 'inAppMessageWillDismiss'
listenerFunc (event: InAppMessageWillDismissEvent) => void

Returns: Promise<PluginListenerHandle>


addListener('inAppMessageDidDismiss', ...)

addListener(eventName: 'inAppMessageDidDismiss', listenerFunc: (event: InAppMessageDidDismissEvent) => void) => Promise<PluginListenerHandle>

Listen for in-app message did dismiss events.

Param Type
eventName 'inAppMessageDidDismiss'
listenerFunc (event: InAppMessageDidDismissEvent) => void

Returns: Promise<PluginListenerHandle>


removeAllListeners()

removeAllListeners() => Promise<void>

Remove all listeners for a specific event.


Interfaces

PluginListenerHandle

Prop Type
remove () => Promise<void>

NotificationClickEvent

Prop Type Description
notification OSNotification The notification that was clicked
result NotificationClickResult The result of the click action

OSNotification

Prop Type Description
body string The message body of the notification
title string The title of the notification
sound string The sound to play when the notification is received
launchURL string URL to launch when the notification is clicked
rawPayload Record<string, unknown> Raw payload from OneSignal
actionButtons OSActionButton[] Action buttons attached to the notification
additionalData Record<string, unknown> Custom additional data attached to the notification
notificationId string Unique identifier for the notification
groupKey string Android: Group key for notification grouping
groupMessage string Android: Summary text for grouped notifications
groupedNotifications OSNotification[] Android: Grouped notifications
ledColor string Android: LED color
priority number Android: Notification priority
smallIcon string Android: Small icon resource name
largeIcon string Android: Large icon URL or resource name
bigPicture string Android: Big picture URL
collapseId string Android: Collapse ID for notification replacement
fromProjectNumber string Android: Project number the notification was sent from
smallIconAccentColor string Android: Accent color for the small icon
lockScreenVisibility number Android: Lock screen visibility
androidNotificationId number Android: Notification ID (integer)
badge number iOS: Badge count
badgeIncrement number iOS: Badge increment
category string iOS: Notification category
threadId string iOS: Thread ID for notification grouping
subtitle string iOS: Subtitle text
templateId string iOS: Template ID
templateName string iOS: Template name
attachments Record<string, string> iOS: Media attachments
mutableContent boolean iOS: Whether content is mutable
contentAvailable boolean iOS: Whether content is available in background
relevanceScore number iOS: Relevance score for notification summary
interruptionLevel string iOS: Interruption level

OSActionButton

Prop Type Description
id string Action button ID
text string Action button text
icon string Action button icon (Android only)

NotificationClickResult

Prop Type Description
actionId string The action ID if an action button was clicked
url string The URL to open

NotificationWillDisplayEvent

Prop Type Description
notification OSNotification The notification to be displayed

PermissionChangedState

Prop Type Description
permission boolean Whether permission is granted

PushSubscriptionChangedState

Prop Type Description
previous PushSubscriptionState The previous subscription state
current PushSubscriptionState The current subscription state

PushSubscriptionState

Prop Type Description
id string The push subscription ID
token string The push token
optedIn boolean Whether the user is opted in to push notifications

UserChangedState

Prop Type Description
current UserState The current user state

UserState

Prop Type Description
onesignalId string The OneSignal user ID
externalId string The external user ID set via login()

InAppMessageClickEvent

Prop Type Description
message OSInAppMessage The in-app message
result InAppMessageClickResult The click result

OSInAppMessage

Prop Type Description
messageId string Unique identifier for the in-app message

InAppMessageClickResult

Prop Type Description
actionId string The action ID
url string The URL to open
urlTarget InAppMessageActionUrlType How to open the URL
closingMessage boolean Whether the in-app message should close

InAppMessageWillDisplayEvent

Prop Type Description
message OSInAppMessage The in-app message

InAppMessageDidDisplayEvent

Prop Type Description
message OSInAppMessage The in-app message

InAppMessageWillDismissEvent

Prop Type Description
message OSInAppMessage The in-app message

InAppMessageDidDismissEvent

Prop Type Description
message OSInAppMessage The in-app message

Type Aliases

Record

Construct a type with a set of properties K of type T

{ [P in K]: T; }

Enums

LogLevel

Members Value
None 0
Fatal 1
Error 2
Warn 3
Info 4
Debug 5
Verbose 6

OSNotificationPermission

Members Value
NotDetermined 0
Denied 1
Authorized 2
Provisional 3
Ephemeral 4

InAppMessageActionUrlType

Members Value
InAppWebview 0
Browser 1
ReplaceContent 2

About

capacitor v8 plugin for OneSignal

Resources

Contributing

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published