@fidaktk/onesignal-capacitor
v1.0.1
Published
Capacitor plugin for OneSignal push notifications SDK v5 — native Android & iOS integration with full event support
Maintainers
Readme
@fidaktk/onesignal-capacitor
Capacitor 8 plugin for OneSignal push notifications (SDK v5). Native Android & iOS -- no Cordova dependency.
Requirements
| Dependency | Version | |--------------------|----------------| | Capacitor | >= 8.0.0 | | Android minSdk | 24 (Android 7) | | iOS deployment | 15.0+ | | OneSignal SDK | 5.x |
Before you start: Create a OneSignal account, set up an app in the dashboard, and grab your App ID. You'll also need platform credentials configured in OneSignal:
- Android: Firebase Cloud Messaging (FCM) server key -- requires a Firebase project
- iOS: APNs authentication key (p8) or certificate (p12) -- from Apple Developer
Install
npm install @fidaktk/onesignal-capacitor
npx cap syncNo manual plugin registration is needed -- Capacitor auto-discovers the plugin.
Android Setup
Download
google-services.jsonfrom your Firebase project and place it inandroid/app/.In your project-level
android/build.gradle, add:buildscript { dependencies { classpath 'com.google.gms:google-services:4.4.0' } }In your app-level
android/app/build.gradle, add at the top:apply plugin: 'com.google.gms.google-services'
That's it. The OneSignal SDK auto-registers its permissions and receivers.
iOS Setup
In Xcode, select your app target > Signing & Capabilities, then add:
- Push Notifications
- Background Modes > check Remote notifications
(Recommended) Add a Notification Service Extension for rich push (images, action buttons, badge counts):
a. File > New > Target > Notification Service Extension. Name it
OneSignalNotificationServiceExtension.b. Set its deployment target to iOS 15.0.
c. Add the extension target to your
ios/App/Podfile:target 'OneSignalNotificationServiceExtension' do use_frameworks! pod 'OneSignalXCFramework', '~> 5.2' endd. Replace
NotificationService.swiftwith:import UserNotifications import OneSignalExtension class NotificationService: UNNotificationServiceExtension { var contentHandler: ((UNNotificationContent) -> Void)? var receivedRequest: UNNotificationRequest! var bestAttemptContent: UNMutableNotificationContent? override func didReceive( _ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void ) { self.receivedRequest = request self.contentHandler = contentHandler self.bestAttemptContent = (request.content.mutableCopy() as? UNMutableNotificationContent) if let bestAttemptContent = bestAttemptContent { OneSignalExtension.didReceiveNotificationExtensionRequest( self.receivedRequest, with: bestAttemptContent, withContentHandler: self.contentHandler ) } } override func serviceExtensionTimeWillExpire() { if let contentHandler = contentHandler, let bestAttemptContent = bestAttemptContent { OneSignalExtension.serviceExtensionTimeWillExpireRequest( self.receivedRequest, with: bestAttemptContent ) contentHandler(bestAttemptContent) } } }e. Run
cd ios/App && pod install.
Quick Start
import { OneSignalPlugin } from '@fidaktk/onesignal-capacitor';
import type {
OneSignalNotification,
PushSubscriptionChangedState,
} from '@fidaktk/onesignal-capacitor';
// Call once at app startup (e.g. app.component.ts, main.ts, App.tsx)
async function initOneSignal() {
// Initialize with your OneSignal App ID
await OneSignalPlugin.initialize({ appId: 'YOUR_ONESIGNAL_APP_ID' });
// Request push permission
const { permission } = await OneSignalPlugin.requestNotificationPermission({
fallbackToSettings: true,
});
console.log('Permission:', permission);
// Handle notification taps (including cold-start launches)
OneSignalPlugin.addListener(
'notificationClicked',
(event: OneSignalNotification) => {
console.log('Clicked:', event.notificationId, event.additionalData);
},
);
// Handle foreground notifications
OneSignalPlugin.addListener(
'notificationWillDisplay',
(event: OneSignalNotification) => {
// Show it (or omit this call to suppress)
OneSignalPlugin.displayNotification({
notificationId: event.notificationId,
});
},
);
// Track push token changes
OneSignalPlugin.addListener(
'pushSubscriptionChange',
(state: PushSubscriptionChangedState) => {
console.log('Token:', state.current.token);
},
);
}Usage
User Identity
// After authentication
await OneSignalPlugin.login({ externalId: 'user-123' });
// On logout
await OneSignalPlugin.logout();Tags
await OneSignalPlugin.addTag({ key: 'plan', value: 'premium' });
await OneSignalPlugin.addTags({ tags: { plan: 'premium', role: 'admin' } });
const { tags } = await OneSignalPlugin.getTags();
await OneSignalPlugin.removeTag({ key: 'plan' });
await OneSignalPlugin.removeTags({ keys: ['plan', 'role'] });Push Subscription
const state = await OneSignalPlugin.getPushSubscriptionState();
console.log(state.token, state.optedIn);
await OneSignalPlugin.optInPushSubscription();
await OneSignalPlugin.optOutPushSubscription();Email & SMS
await OneSignalPlugin.addEmail({ email: '[email protected]' });
await OneSignalPlugin.addSms({ smsNumber: '+15551234567' });In-App Messages
await OneSignalPlugin.addInAppMessageTrigger({ key: 'screen', value: 'home' });
await OneSignalPlugin.setInAppMessagesPaused({ paused: true });
OneSignalPlugin.addListener('inAppMessageClicked', (action) => {
console.log(action.clickName, action.clickUrl);
});Outcomes
await OneSignalPlugin.addOutcome({ name: 'purchase' });
await OneSignalPlugin.addUniqueOutcome({ name: 'app_open' });
await OneSignalPlugin.addOutcomeWithValue({ name: 'revenue', value: 9.99 });GDPR Consent
// Call BEFORE initialize()
await OneSignalPlugin.setConsentRequired({ required: true });
// After user consents
await OneSignalPlugin.setConsentGiven({ given: true });
// Then initialize
await OneSignalPlugin.initialize({ appId: 'YOUR_APP_ID' });Debug Logging
import { LogLevel } from '@fidaktk/onesignal-capacitor';
// Set before initialize() to capture init logs
await OneSignalPlugin.setLogLevel({ level: LogLevel.Verbose });
await OneSignalPlugin.initialize({ appId: 'YOUR_APP_ID' });Foreground Notifications
When a notification arrives while the app is in the foreground, the notificationWillDisplay event fires. The notification is not shown automatically -- you decide:
OneSignalPlugin.addListener('notificationWillDisplay', (event) => {
// Option A: Show it
OneSignalPlugin.displayNotification({ notificationId: event.notificationId });
// Option B: Do nothing (suppressed)
});If you don't call displayNotification within 25 seconds, it auto-displays as a safety fallback.
API
initialize(...)login(...)logout()setConsentRequired(...)setConsentGiven(...)addTag(...)addTags(...)getTags()removeTag(...)removeTags(...)addAlias(...)addAliases(...)removeAlias(...)removeAliases(...)addEmail(...)removeEmail(...)addSms(...)removeSms(...)setLanguage(...)getPushSubscriptionState()optInPushSubscription()optOutPushSubscription()requestNotificationPermission(...)getNotificationPermission()canRequestNotificationPermission()displayNotification(...)addInAppMessageTrigger(...)addInAppMessageTriggers(...)removeInAppMessageTrigger(...)removeInAppMessageTriggers(...)clearInAppMessageTriggers()setInAppMessagesPaused(...)getInAppMessagesPaused()addOutcome(...)addUniqueOutcome(...)addOutcomeWithValue(...)setLocationShared(...)requestLocationPermission()setLogLevel(...)setAlertLevel(...)addListener('notificationClicked', ...)addListener('notificationWillDisplay', ...)addListener('pushSubscriptionChange', ...)addListener('permissionChange', ...)addListener('inAppMessageClicked', ...)addListener('inAppMessageLifecycle', ...)removeAllListeners()- Interfaces
- Type Aliases
initialize(...)
initialize(options: { appId: string; }) => Promise<void>Initialize the OneSignal SDK. Must be called before any other method.
| Param | Type |
| ------------- | ------------------------------- |
| options | { appId: string; } |
login(...)
login(options: { externalId: string; }) => Promise<void>Identify the current user by an external ID. Call on every app launch when you know the user's identity. Creates or retrieves the OneSignal user associated with this external ID.
| Param | Type |
| ------------- | ------------------------------------ |
| options | { externalId: string; } |
logout()
logout() => Promise<void>Log the user out. Reverts to an anonymous device-scoped user.
setConsentRequired(...)
setConsentRequired(options: { required: boolean; }) => Promise<void>Require user consent before the SDK collects any data. Must be called before {@link initialize}.
| Param | Type |
| ------------- | ----------------------------------- |
| options | { required: boolean; } |
setConsentGiven(...)
setConsentGiven(options: { given: boolean; }) => Promise<void>Indicate that the user has given (or revoked) data collection consent.
| Param | Type |
| ------------- | -------------------------------- |
| options | { given: boolean; } |
addTag(...)
addTag(options: { key: string; value: string; }) => Promise<void>Set a single tag on the current user.
| Param | Type |
| ------------- | -------------------------------------------- |
| options | { key: string; value: string; } |
addTags(...)
addTags(options: { tags: Record<string, string>; }) => Promise<void>Set multiple tags on the current user at once.
| Param | Type |
| ------------- | -------------------------------------------------------------------------- |
| options | { tags: Record<string, string>; } |
getTags()
getTags() => Promise<{ tags: Record<string, string>; }>Get all tags currently set on the user (local cache).
Returns: Promise<{ tags: Record<string, string>; }>
removeTag(...)
removeTag(options: { key: string; }) => Promise<void>Remove a single tag from the current user.
| Param | Type |
| ------------- | ----------------------------- |
| options | { key: string; } |
removeTags(...)
removeTags(options: { keys: string[]; }) => Promise<void>Remove multiple tags from the current user at once.
| Param | Type |
| ------------- | -------------------------------- |
| options | { keys: string[]; } |
addAlias(...)
addAlias(options: { label: string; id: string; }) => Promise<void>Add an alias for the current user.
| Param | Type |
| ------------- | ------------------------------------------- |
| options | { label: string; id: string; } |
addAliases(...)
addAliases(options: { aliases: Record<string, string>; }) => Promise<void>Add multiple aliases for the current user at once.
| Param | Type |
| ------------- | ----------------------------------------------------------------------------- |
| options | { aliases: Record<string, string>; } |
removeAlias(...)
removeAlias(options: { label: string; }) => Promise<void>Remove an alias from the current user.
| Param | Type |
| ------------- | ------------------------------- |
| options | { label: string; } |
removeAliases(...)
removeAliases(options: { labels: string[]; }) => Promise<void>Remove multiple aliases from the current user at once.
| Param | Type |
| ------------- | ---------------------------------- |
| options | { labels: string[]; } |
addEmail(...)
addEmail(options: { email: string; }) => Promise<void>Add an email subscription to the current user.
| Param | Type |
| ------------- | ------------------------------- |
| options | { email: string; } |
removeEmail(...)
removeEmail(options: { email: string; }) => Promise<void>Remove an email subscription from the current user.
| Param | Type |
| ------------- | ------------------------------- |
| options | { email: string; } |
addSms(...)
addSms(options: { smsNumber: string; }) => Promise<void>Add an SMS subscription to the current user.
| Param | Type |
| ------------- | ----------------------------------- |
| options | { smsNumber: string; } |
removeSms(...)
removeSms(options: { smsNumber: string; }) => Promise<void>Remove an SMS subscription from the current user.
| Param | Type |
| ------------- | ----------------------------------- |
| options | { smsNumber: string; } |
setLanguage(...)
setLanguage(options: { language: string; }) => Promise<void>Override the auto-detected device language for the current user.
| Param | Type |
| ------------- | ---------------------------------- |
| options | { language: string; } |
getPushSubscriptionState()
getPushSubscriptionState() => Promise<PushSubscriptionState>Get the current push subscription state (ID, token, opted-in status).
Returns: Promise<PushSubscriptionState>
optInPushSubscription()
optInPushSubscription() => Promise<void>Opt the current device into push notifications.
optOutPushSubscription()
optOutPushSubscription() => Promise<void>Opt the current device out of push notifications.
requestNotificationPermission(...)
requestNotificationPermission(options?: { fallbackToSettings?: boolean | undefined; } | undefined) => Promise<{ permission: boolean; }>Show the native push notification permission prompt.
| Param | Type |
| ------------- | ---------------------------------------------- |
| options | { fallbackToSettings?: boolean; } |
Returns: Promise<{ permission: boolean; }>
getNotificationPermission()
getNotificationPermission() => Promise<{ permission: boolean; }>Check the current notification permission status without prompting.
Returns: Promise<{ permission: boolean; }>
canRequestNotificationPermission()
canRequestNotificationPermission() => Promise<{ canRequest: boolean; }>Check whether the permission prompt can be shown (i.e., user hasn't permanently denied it).
Returns: Promise<{ canRequest: boolean; }>
displayNotification(...)
displayNotification(options: { notificationId: string; }) => Promise<void>Display a foreground notification that was intercepted by the
notificationWillDisplay listener. If not called within 25 seconds,
the notification displays automatically.
| Param | Type |
| ------------- | ---------------------------------------- |
| options | { notificationId: string; } |
addInAppMessageTrigger(...)
addInAppMessageTrigger(options: { key: string; value: string; }) => Promise<void>Add a trigger that controls when in-app messages are displayed.
| Param | Type |
| ------------- | -------------------------------------------- |
| options | { key: string; value: string; } |
addInAppMessageTriggers(...)
addInAppMessageTriggers(options: { triggers: Record<string, string>; }) => Promise<void>Add multiple in-app message triggers at once.
| Param | Type |
| ------------- | ------------------------------------------------------------------------------ |
| options | { triggers: Record<string, string>; } |
removeInAppMessageTrigger(...)
removeInAppMessageTrigger(options: { key: string; }) => Promise<void>Remove an in-app message trigger.
| Param | Type |
| ------------- | ----------------------------- |
| options | { key: string; } |
removeInAppMessageTriggers(...)
removeInAppMessageTriggers(options: { keys: string[]; }) => Promise<void>Remove multiple in-app message triggers at once.
| Param | Type |
| ------------- | -------------------------------- |
| options | { keys: string[]; } |
clearInAppMessageTriggers()
clearInAppMessageTriggers() => Promise<void>Remove all in-app message triggers.
setInAppMessagesPaused(...)
setInAppMessagesPaused(options: { paused: boolean; }) => Promise<void>Pause or resume in-app message display.
| Param | Type |
| ------------- | --------------------------------- |
| options | { paused: boolean; } |
getInAppMessagesPaused()
getInAppMessagesPaused() => Promise<{ paused: boolean; }>Check if in-app messages are currently paused.
Returns: Promise<{ paused: boolean; }>
addOutcome(...)
addOutcome(options: { name: string; }) => Promise<void>Track a custom outcome event.
| Param | Type |
| ------------- | ------------------------------ |
| options | { name: string; } |
addUniqueOutcome(...)
addUniqueOutcome(options: { name: string; }) => Promise<void>Track a unique outcome (counted only once per session).
| Param | Type |
| ------------- | ------------------------------ |
| options | { name: string; } |
addOutcomeWithValue(...)
addOutcomeWithValue(options: { name: string; value: number; }) => Promise<void>Track an outcome with a numeric value (e.g. revenue).
| Param | Type |
| ------------- | --------------------------------------------- |
| options | { name: string; value: number; } |
setLocationShared(...)
setLocationShared(options: { shared: boolean; }) => Promise<void>Enable or disable sharing the user's location with OneSignal.
| Param | Type |
| ------------- | --------------------------------- |
| options | { shared: boolean; } |
requestLocationPermission()
requestLocationPermission() => Promise<void>Request location permission from the user.
setLogLevel(...)
setLogLevel(options: { level: number; }) => Promise<void>Set the SDK log output level.
| Param | Type |
| ------------- | ------------------------------- |
| options | { level: number; } |
setAlertLevel(...)
setAlertLevel(options: { level: number; }) => Promise<void>Set the log level for alert dialogs (shown to the user on device).
| Param | Type |
| ------------- | ------------------------------- |
| options | { level: number; } |
addListener('notificationClicked', ...)
addListener(eventName: 'notificationClicked', listenerFunc: (event: OneSignalNotification) => void) => Promise<PluginListenerHandle>Fired when the user taps a notification (including cold-start launches).
| Param | Type |
| ------------------ | ------------------------------------------------------------------------------------------- |
| eventName | 'notificationClicked' |
| listenerFunc | (event: OneSignalNotification) => void |
Returns: Promise<PluginListenerHandle>
addListener('notificationWillDisplay', ...)
addListener(eventName: 'notificationWillDisplay', listenerFunc: (event: OneSignalNotification) => void) => Promise<PluginListenerHandle>Fired when a notification is received while the app is in the foreground.
Call {@link displayNotification} with the notificationId to show it,
or do nothing to suppress it.
| Param | Type |
| ------------------ | ------------------------------------------------------------------------------------------- |
| eventName | 'notificationWillDisplay' |
| listenerFunc | (event: OneSignalNotification) => void |
Returns: Promise<PluginListenerHandle>
addListener('pushSubscriptionChange', ...)
addListener(eventName: 'pushSubscriptionChange', listenerFunc: (event: PushSubscriptionChangedState) => void) => Promise<PluginListenerHandle>Fired when the push subscription state changes (token, opt-in status).
| Param | Type |
| ------------------ | --------------------------------------------------------------------------------------------------------- |
| eventName | 'pushSubscriptionChange' |
| listenerFunc | (event: PushSubscriptionChangedState) => void |
Returns: Promise<PluginListenerHandle>
addListener('permissionChange', ...)
addListener(eventName: 'permissionChange', listenerFunc: (event: { permission: boolean; }) => void) => Promise<PluginListenerHandle>Fired when notification permission status changes.
| Param | Type |
| ------------------ | --------------------------------------------------------- |
| eventName | 'permissionChange' |
| listenerFunc | (event: { permission: boolean; }) => void |
Returns: Promise<PluginListenerHandle>
addListener('inAppMessageClicked', ...)
addListener(eventName: 'inAppMessageClicked', listenerFunc: (event: InAppMessageAction) => void) => Promise<PluginListenerHandle>Fired when the user clicks an element in an in-app message.
| Param | Type |
| ------------------ | ------------------------------------------------------------------------------------- |
| eventName | 'inAppMessageClicked' |
| listenerFunc | (event: InAppMessageAction) => void |
Returns: Promise<PluginListenerHandle>
addListener('inAppMessageLifecycle', ...)
addListener(eventName: 'inAppMessageLifecycle', listenerFunc: (event: InAppMessageLifecycleEvent) => void) => Promise<PluginListenerHandle>Fired during in-app message lifecycle transitions.
| Param | Type |
| ------------------ | ----------------------------------------------------------------------------------------------------- |
| eventName | 'inAppMessageLifecycle' |
| listenerFunc | (event: InAppMessageLifecycleEvent) => void |
Returns: Promise<PluginListenerHandle>
removeAllListeners()
removeAllListeners() => Promise<void>Remove all registered event listeners.
Interfaces
PushSubscriptionState
Current state of the device's push subscription.
| Prop | Type | Description |
| ------------- | -------------------- | --------------------------------------------------- |
| id | string | OneSignal subscription ID for this device. |
| token | string | Push token (FCM on Android, APNs on iOS). |
| optedIn | boolean | Whether the user is opted in to push notifications. |
PluginListenerHandle
| Prop | Type |
| ------------ | ----------------------------------------- |
| remove | () => Promise<void> |
OneSignalNotification
Represents a OneSignal push notification.
| Prop | Type | Description |
| -------------------- | ---------------------------------------------------------------- | ---------------------------------------------------------------- |
| notificationId | string | Unique notification identifier. |
| title | string | Notification title. |
| body | string | Notification body text. |
| sound | string | Sound file name. |
| badgeCount | number | Badge count (iOS). |
| launchUrl | string | URL to open when notification is tapped. |
| rawPayload | string | Raw notification payload as a JSON string. |
| additionalData | Record<string, unknown> | Custom key-value data attached to the notification. |
| actionId | string | Action button ID that was tapped (only present on click events). |
PushSubscriptionChangedState
Emitted when push subscription state changes.
| Prop | Type | Description |
| -------------- | ----------------------------------------------------------------------- | ---------------------------- |
| previous | PushSubscriptionState | Previous subscription state. |
| current | PushSubscriptionState | Current subscription state. |
InAppMessageAction
Data from an in-app message click event.
| Prop | Type | Description |
| ------------------- | -------------------- | ------------------------------------------------ |
| clickName | string | Action element name that was clicked. |
| clickUrl | string | URL associated with the clicked element. |
| firstClick | boolean | Whether this is the first click on this message. |
| closesMessage | boolean | Whether this click closes the message. |
InAppMessageLifecycleEvent
In-app message lifecycle event.
| Prop | Type | Description |
| --------------- | --------------------------------------------------------------------------- | -------------------------- |
| type | 'willDisplay' | 'didDisplay' | 'willDismiss' | 'didDismiss' | Lifecycle stage. |
| messageId | string | Unique message identifier. |
Type Aliases
Record
Construct a type with a set of properties K of type T
{ [P in K]: T; }
Contributing
See CONTRIBUTING.md.
