@onesignal/capacitor-plugin
v1.0.1
Published
OneSignal is a high volume Push Notification service for mobile apps. This is the pure Capacitor plugin for OneSignal, providing push notifications, in-app messaging, and more.
Readme
OneSignal-Capacitor-SDK
The pure Capacitor plugin for OneSignal, providing push notifications, in-app messaging, live activities, and more.
Install
npm install @onesignal/capacitor-plugin
npx cap syncUsage
import OneSignal from '@onesignal/capacitor-plugin';
await OneSignal.initialize({ appId: 'YOUR_ONESIGNAL_APP_ID' });
await OneSignal.Notifications.requestPermission(true);See the examples/demo directory for a full working example.
API
The public OneSignal Capacitor plugin API. This is the shape of the default OneSignal export.
initialize(...)
initialize(appId: string) => Promise<void>Initialize the SDK with your OneSignal app ID. Call during app startup.
| Param | Type |
| ----------- | ------------------- |
| appId | string |
login(...)
login(externalId: string) => Promise<void>Log in to OneSignal as the user identified by externalId, switching the user context.
| Param | Type |
| ---------------- | ------------------- |
| externalId | string |
logout()
logout() => Promise<void>Log out the current user. The SDK will reference a new device-scoped user.
setConsentRequired(...)
setConsentRequired(required: boolean) => voidSet whether user privacy consent is required before sending data to OneSignal. Call before initialize.
| Param | Type |
| -------------- | -------------------- |
| required | boolean |
setConsentGiven(...)
setConsentGiven(granted: boolean) => voidIndicate whether the user has granted privacy consent.
| Param | Type |
| ------------- | -------------------- |
| granted | boolean |
Interfaces
OneSignalDebugAPI
Debug helpers exposed via OneSignal.Debug.
| Method | Signature | Description | | ----------------- | ------------------------------------------------------------- | ------------------------------------------------------------------------- | | setLogLevel | (logLevel: LogLevel) => void | Set the log level printed to LogCat (Android) or the Xcode console (iOS). | | setAlertLevel | (visualLogLevel: LogLevel) => void | Set the log level shown to the user as alert dialogs. |
OneSignalUserAPI
Current-user operations exposed via OneSignal.User.
| Prop | Type | Description |
| ---------------------- | ------------------------------------------------------------------------------------- | ------------------------------------------------ |
| pushSubscription | OneSignalPushSubscriptionAPI | Push subscription controls for the current user. |
| Method | Signature | Description |
| ----------------------- | ------------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------- |
| setLanguage | (language: string) => Promise<void> | Explicitly set a 2-character language code for the current user. |
| addAlias | (label: string, id: string) => Promise<void> | Add or overwrite a single alias on the current user. |
| addAliases | (aliases: Record<string, string>) => Promise<void> | Add or overwrite multiple aliases on the current user. |
| removeAlias | (label: string) => Promise<void> | Remove a single alias by label from the current user. |
| removeAliases | (labels: string[]) => Promise<void> | Remove multiple aliases by label from the current user. |
| addEmail | (email: string) => Promise<void> | Add a new email subscription to the current user. |
| removeEmail | (email: string) => Promise<void> | Remove an email subscription from the current user. |
| addSms | (smsNumber: string) => Promise<void> | Add a new SMS subscription to the current user. |
| removeSms | (smsNumber: string) => Promise<void> | Remove an SMS subscription from the current user. |
| addTag | (key: string, value: string) => Promise<void> | Add a single tag (key/value) on the current user, used for targeting and personalization. |
| addTags | (tags: object) => Promise<void> | Add or overwrite multiple tags on the current user. |
| removeTag | (key: string) => Promise<void> | Remove a single tag by key from the current user. |
| removeTags | (keys: string[]) => Promise<void> | Remove multiple tags by key from the current user. |
| getTags | () => Promise<{ [key: string]: string; }> | Get the local tags for the current user. |
| addEventListener | (event: 'change', listener: (event: UserChangedState) => void) => void | Add a listener for OneSignal user state changes. |
| removeEventListener | (event: 'change', listener: (event: UserChangedState) => void) => void | Remove a previously added user state listener. |
| getOnesignalId | () => Promise<string | null> | Get the OneSignal-assigned ID for the current user, or null if not yet available. |
| getExternalId | () => Promise<string | null> | Get the external ID set via login, or null if the user is anonymous. |
| trackEvent | (name: string, properties?: object | undefined) => Promise<void> | Track a custom event with an optional set of JSON-serializable properties. |
UserChangedState
| Prop | Type |
| ------------- | ----------------------------------------------- |
| current | UserState |
UserState
| Prop | Type |
| ----------------- | ------------------- |
| onesignalId | string |
| externalId | string |
OneSignalPushSubscriptionAPI
Push subscription state and controls exposed via OneSignal.User.pushSubscription.
| Method | Signature | Description |
| ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| getIdAsync | () => Promise<string | null> | Get the current device's push subscription ID, or null if not yet assigned. |
| getTokenAsync | () => Promise<string | null> | Get the current device's push token, or null if not yet available. |
| getOptedInAsync | () => Promise<boolean> | Whether the current user is opted in to push notifications. Returns true when the app has notification permission and optOut() has not been called. Does not guarantee a token has been received. |
| addEventListener | (event: 'change', listener: (event: PushSubscriptionChangedState) => void) => void | Add a listener for push subscription state changes. |
| removeEventListener | (event: 'change', listener: (event: PushSubscriptionChangedState) => void) => void | Remove a previously added push subscription state listener. |
| optIn | () => Promise<void> | Opt the user in to push notifications. Prompts for permission if needed. |
| optOut | () => Promise<void> | Opt the user out of push notifications on this device. |
PushSubscriptionChangedState
| Prop | Type |
| -------------- | ----------------------------------------------------------------------- |
| previous | PushSubscriptionState |
| current | PushSubscriptionState |
PushSubscriptionState
| Prop | Type |
| ------------- | -------------------- |
| id | string |
| token | string |
| optedIn | boolean |
OneSignalNotificationsAPI
Notification permission and event handling exposed via OneSignal.Notifications.
| Method | Signature | Description |
| --------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------- |
| hasPermission | () => Promise<boolean> | Whether the app currently has notification permission (including provisional/ephemeral). |
| permissionNative | () => Promise<OSNotificationPermission> | iOS only. The native notification permission status. |
| requestPermission | (fallbackToSettings?: boolean | undefined) => Promise<boolean> | Prompt the user for notification permission. Optionally fall back to system settings. |
| canRequestPermission | () => Promise<boolean> | Whether requesting notification permission would still show a prompt. |
| registerForProvisionalAuthorization | (handler?: ((response: boolean) => void) | undefined) => void | iOS only. Request provisional authorization for quiet notifications without prompting. |
| addEventListener | <K extends NotificationEventName>(event: K, listener: (event: NotificationEventTypeMap[K]) => void) => void | Add a listener for click, foregroundWillDisplay, or permissionChange events. |
| removeEventListener | <K extends NotificationEventName>(event: K, listener: (obj: NotificationEventTypeMap[K]) => void) => void | Remove a previously added notification event listener. |
| clearAll | () => Promise<void> | Remove all OneSignal notifications from the notification center. |
| removeNotification | (id: number) => Promise<void> | Android only. Cancel a single notification by its Android notification ID. |
| removeGroupedNotifications | (id: string) => Promise<void> | Android only. Cancel a group of notifications by group key. |
NotificationClickEvent
| Prop | Type |
| ------------------ | --------------------------------------------------------------------------- |
| result | NotificationClickResult |
| notification | OSNotification |
NotificationClickResult
| Prop | Type |
| -------------- | ------------------- |
| actionId | string |
| url | string |
OneSignalInAppMessagesAPI
In-app message triggers and event handling exposed via OneSignal.InAppMessages.
| Method | Signature | Description |
| ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------- |
| addEventListener | <K extends InAppMessageEventName>(event: K, listener: (event: InAppMessageEventTypeMap[K]) => void) => void | Add a listener for IAM click, willDisplay, didDisplay, willDismiss, or didDismiss events. |
| removeEventListener | <K extends InAppMessageEventName>(event: K, listener: (obj: InAppMessageEventTypeMap[K]) => void) => void | Remove a previously added IAM event listener. |
| addTrigger | (key: string, value: string) => Promise<void> | Add a single trigger (key/value) used to determine which IAMs are displayed to the user. |
| addTriggers | (triggers: { [key: string]: string; }) => Promise<void> | Add or overwrite multiple triggers for the current user. |
| removeTrigger | (key: string) => Promise<void> | Remove a single trigger by key. |
| removeTriggers | (keys: string[]) => Promise<void> | Remove multiple triggers by key. |
| clearTriggers | () => Promise<void> | Clear all triggers from the current user. |
| setPaused | (pause: boolean) => void | Pause or resume the display of in-app messages. |
| getPaused | () => Promise<boolean> | Whether in-app messaging is currently paused. |
InAppMessageClickEvent
| Prop | Type |
| ------------- | --------------------------------------------------------------------------- |
| message | OSInAppMessage |
| result | InAppMessageClickResult |
OSInAppMessage
| Prop | Type |
| --------------- | ------------------- |
| messageId | string |
InAppMessageClickResult
| Prop | Type |
| -------------------- | ------------------------------------------------------------------------------- |
| closingMessage | boolean |
| actionId | string |
| url | string |
| urlTarget | InAppMessageActionUrlType |
InAppMessageWillDisplayEvent
| Prop | Type |
| ------------- | --------------------------------------------------------- |
| message | OSInAppMessage |
InAppMessageDidDisplayEvent
| Prop | Type |
| ------------- | --------------------------------------------------------- |
| message | OSInAppMessage |
InAppMessageWillDismissEvent
| Prop | Type |
| ------------- | --------------------------------------------------------- |
| message | OSInAppMessage |
InAppMessageDidDismissEvent
| Prop | Type |
| ------------- | --------------------------------------------------------- |
| message | OSInAppMessage |
OneSignalSessionAPI
Outcome reporting exposed via OneSignal.Session.
| Method | Signature | Description | | ----------------------- | ------------------------------------------------------- | -------------------------------------------------------------------------------------------------- | | addOutcome | (name: string) => Promise<void> | Record an outcome with the given name against the current session. | | addUniqueOutcome | (name: string) => Promise<void> | Record a unique outcome with the given name against the current session. | | addOutcomeWithValue | (name: string, value: number) => Promise<void> | Record an outcome with the given name and value against the current session. |
OneSignalLocationAPI
Location permission and sharing exposed via OneSignal.Location.
| Method | Signature | Description | | --------------------- | ------------------------------- | --------------------------------------------------------------- | | requestPermission | () => Promise<void> | Prompt the user for location permission to enable geotagging. | | setShared | (shared: boolean) => void | Enable or disable sharing the device location with OneSignal. | | isShared | () => Promise<boolean> | Whether the device location is currently shared with OneSignal. |
OneSignalLiveActivitiesAPI
Live activity controls exposed via OneSignal.LiveActivities. iOS only unless noted.
| Method | Signature | Description |
| -------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------- |
| enter | (activityId: string, token: string, onSuccess?: ((data: unknown) => void) | undefined, onFailure?: ((data: unknown) => void) | undefined) => void | Associate a live activity ID with a push token so OneSignal can target it. |
| exit | (activityId: string, onSuccess?: ((data: unknown) => void) | undefined, onFailure?: ((data: unknown) => void) | undefined) => void | Disassociate a live activity ID. |
| setPushToStartToken | (activityType: string, token: string) => Promise<void> | Register a pushToStart token for the given live activity attributes type. |
| removePushToStartToken | (activityType: string) => Promise<void> | Remove a previously registered pushToStart token for the given attributes type. |
| setupDefault | (options?: LiveActivitySetupOptions | undefined) => Promise<void> | Set up the OneSignal default live activity, optionally enabling pushToStart/pushToUpdate. |
| startDefault | (activityId: string, attributes: Record<string, unknown>, content: Record<string, unknown>) => Promise<void> | Start a live activity backed by the OneSignal default attributes type. |
Type Aliases
LogLevel
(typeof LogLevel)[keyof typeof LogLevel]
Record
Construct a type with a set of properties K of type T
{ [P in K]: T; }
OSNotificationPermission
(typeof OSNotificationPermission)[keyof typeof OSNotificationPermission]
NotificationEventName
'click' | 'foregroundWillDisplay' | 'permissionChange'
NotificationEventTypeMap
{ click: NotificationClickEvent; foregroundWillDisplay: NotificationWillDisplayEvent; permissionChange: boolean; }
InAppMessageEventName
'click' | 'willDisplay' | 'didDisplay' | 'willDismiss' | 'didDismiss'
InAppMessageEventTypeMap
{ click: InAppMessageClickEvent; willDisplay: InAppMessageWillDisplayEvent; didDisplay: InAppMessageDidDisplayEvent; willDismiss: InAppMessageWillDismissEvent; didDismiss: InAppMessageDidDismissEvent; }
InAppMessageActionUrlType
'browser' | 'webview' | 'replacement'
LiveActivitySetupOptions
The setup options for OneSignal.LiveActivities.setupDefault.
{ /** _ When true, OneSignal will listen for pushToStart tokens for the OneSignalLiveActivityAttributes structure. _/ enablePushToStart: boolean; /** _ When true, OneSignal will listen for pushToUpdate tokens for each start live activity that uses the _ OneSignalLiveActivityAttributes structure. */ enablePushToUpdate: boolean; }
