The Push Notifications API provides access to native push notifications. This plugin is a fork of the Official Capacitor Push Notifications plugin, with the addition of extra configuration options for Android foreground notifications.
npm install @haylltd/capacitor-push-notifications
npx cap sync
On iOS you must enable the Push Notifications capability. See Setting Capabilities for instructions on how to enable the capability.
After enabling the Push Notifications capability, add the following to your app's AppDelegate.swift
:
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
NotificationCenter.default.post(name: .capacitorDidRegisterForRemoteNotifications, object: deviceToken)
}
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
NotificationCenter.default.post(name: .capacitorDidFailToRegisterForRemoteNotifications, object: error)
}
The Push Notification API uses Firebase Cloud Messaging SDK for handling notifications. See Set up a Firebase Cloud Messaging client app on Android and follow the instructions for creating a Firebase project and registering your application. There is no need to add the Firebase SDK to your app or edit your app manifest - the Push Notifications provides that for you. All that is required is your Firebase project's google-services.json
file added to the module (app-level) directory of your app.
This plugin will use the following project variables (defined in your app's variables.gradle
file):
$firebaseMessagingVersion
version ofcom.google.firebase:firebase-messaging
(default:23.0.5
)
On Android, the Push Notifications icon with the appropriate name should be added to the AndroidManifest.xml
file:
<meta-data android:name="com.google.firebase.messaging.default_notification_icon" android:resource="@mipmap/push_icon_name" />
If no icon is specified Android will use the application icon, but push icon should be white pixels on a transparent backdrop. As the application icon is not usually like that, it will show a white square or circle. So it's recommended to provide the separate icon for Push Notifications.
Android Studio has an icon generator you can use to create your Push Notifications icon.
You can configure the way the push notifications are displayed when the app is in foreground.
Prop | Type | Description | Since |
---|---|---|---|
presentationOptions |
{} |
This is an array of strings you can combine. Possible values in the array are: - badge : badge count on the app icon is updated (default value) - sound : the device will ring/vibrate when the push notification is received - alert : the push notification is displayed in a native dialog An empty array can be provided if none of the options are desired. badge is only available for iOS. |
1.0.0 |
androidForegroundChannelId |
AndroidForegroundChannelOption |
The channel for android foreground notifications. - 'default': Use the default channel for foreground notifications. - 'auto': Use the channel specified in the notification for foreground notifications. - string: Use the specified channel for foreground notifications. You must create the channel manually. | 1.0.0 |
androidForegroundChannelName |
string |
The name of the channel for android background notifications if using 'default' for androidForegroundChannelId. | 1.0.0 |
androidForegroundChannelDescription |
string |
The description of the channel for android background notifications if using 'default' for androidForegroundChannelId. | 1.0.0 |
androidForegroundChannelSound |
string |
The sound for the notification channel if using 'default' for androidForegroundChannelId. This is the name of the sound file in the app's raw folder. | 1.0.0 |
In capacitor.config.json
:
{
"plugins": {
"PushNotifications": {
"presentationOptions": ["badge", "sound", "alert"],
"androidForegroundChannelId": "default",
"androidForegroundChannelName": "MyNotificationChannel",
"androidForegroundChannelDescription": "Notifications for my app",
"androidForegroundChannelSound": "my_notification_sound"
}
}
}
In capacitor.config.ts
:
/// <reference types="@haylltd/capacitor-push-notifications" />
import { CapacitorConfig } from '@capacitor/cli';
const config: CapacitorConfig = {
plugins: {
PushNotifications: {
presentationOptions: ["badge", "sound", "alert"],
androidForegroundChannelId: "default",
androidForegroundChannelName: "MyNotificationChannel",
androidForegroundChannelDescription: "Notifications for my app",
androidForegroundChannelSound: "my_notification_sound",
},
},
};
export default config;
This plugin does not support iOS Silent Push (Remote Notifications). We recommend using native code solutions for handling these types of notifications, see Pushing Background Updates to Your App.
This plugin does support data-only notifications, but will NOT call pushNotificationReceived
if the app has been killed. To handle this scenario, you will need to create a service that extends FirebaseMessagingService
, see Handling FCM Messages.
On Android, there are various system and app states that can affect the delivery of push notifications:
- If the device has entered Doze mode, your application may have restricted capabilities. To increase the chance of your notification being received, consider using FCM high priority messages.
- There are differences in behavior between development and production. Try testing your app outside of being launched by Android Studio. Read more here.
import { PushNotifications } from '@capacitor/push-notifications';
const addListeners = async () => {
await PushNotifications.addListener('registration', token => {
console.info('Registration token: ', token.value);
});
await PushNotifications.addListener('registrationError', err => {
console.error('Registration error: ', err.error);
});
await PushNotifications.addListener(
'pushNotificationReceived',
notification => {
console.log('Push notification received: ', notification);
},
);
await PushNotifications.addListener(
'pushNotificationActionPerformed',
notification => {
console.log(
'Push notification action performed',
notification.actionId,
notification.inputValue,
);
},
);
};
const registerNotifications = async () => {
let permStatus = await PushNotifications.checkPermissions();
if (permStatus.receive === 'prompt') {
permStatus = await PushNotifications.requestPermissions();
}
if (permStatus.receive !== 'granted') {
throw new Error('User denied permissions!');
}
await PushNotifications.register();
};
const getDeliveredNotifications = async () => {
const notificationList = await PushNotifications.getDeliveredNotifications();
console.log('delivered notifications', notificationList);
};
register()
getDeliveredNotifications()
removeDeliveredNotifications(...)
removeAllDeliveredNotifications()
createChannel(...)
deleteChannel(...)
listChannels()
checkPermissions()
requestPermissions()
addListener('registration', ...)
addListener('registrationError', ...)
addListener('pushNotificationReceived', ...)
addListener('pushNotificationActionPerformed', ...)
removeAllListeners()
- Interfaces
- Type Aliases
register() => any
Register the app to receive push notifications.
This method will trigger the 'registration'
event with the push token or
'registrationError'
if there was a problem. It does not prompt the user for
notification permissions, use requestPermissions()
first.
Returns: any
Since: 1.0.0
getDeliveredNotifications() => any
Get a list of notifications that are visible on the notifications screen.
Returns: any
Since: 1.0.0
removeDeliveredNotifications(delivered: DeliveredNotifications) => any
Remove the specified notifications from the notifications screen.
Param | Type |
---|---|
delivered |
DeliveredNotifications |
Returns: any
Since: 1.0.0
removeAllDeliveredNotifications() => any
Remove all the notifications from the notifications screen.
Returns: any
Since: 1.0.0
createChannel(channel: Channel) => any
Create a notification channel.
Only available on Android O or newer (SDK 26 ).
Param | Type |
---|---|
channel |
Channel |
Returns: any
Since: 1.0.0
deleteChannel(args: { id: string; }) => any
Delete a notification channel.
Only available on Android O or newer (SDK 26 ).
Param | Type |
---|---|
args |
{ id: string; } |
Returns: any
Since: 1.0.0
listChannels() => any
List the available notification channels.
Only available on Android O or newer (SDK 26 ).
Returns: any
Since: 1.0.0
checkPermissions() => any
Check permission to receive push notifications.
On Android the status is always granted because you can always receive push notifications. If you need to check if the user allows to display notifications, use local-notifications plugin.
Returns: any
Since: 1.0.0
requestPermissions() => any
Request permission to receive push notifications.
On Android it doesn't prompt for permission because you can always receive push notifications.
On iOS, the first time you use the function, it will prompt the user for push notification permission and return granted or denied based on the user selection. On following calls it will get the current status of the permission without prompting again.
Returns: any
Since: 1.0.0
addListener(eventName: 'registration', listenerFunc: (token: Token) => void) => Promise<PluginListenerHandle> & PluginListenerHandle
Called when the push notification registration finishes without problems.
Provides the push notification token.
Param | Type |
---|---|
eventName |
'registration' |
listenerFunc |
(token: Token) => void |
Returns: any
Since: 1.0.0
addListener(eventName: 'registrationError', listenerFunc: (error: RegistrationError) => void) => Promise<PluginListenerHandle> & PluginListenerHandle
Called when the push notification registration finished with problems.
Provides an error with the registration problem.
Param | Type |
---|---|
eventName |
'registrationError' |
listenerFunc |
(error: RegistrationError) => void |
Returns: any
Since: 1.0.0
addListener(eventName: 'pushNotificationReceived', listenerFunc: (notification: PushNotificationSchema) => void) => Promise<PluginListenerHandle> & PluginListenerHandle
Called when the device receives a push notification.
Param | Type |
---|---|
eventName |
'pushNotificationReceived' |
listenerFunc |
(notification: PushNotificationSchema) => void |
Returns: any
Since: 1.0.0
addListener(eventName: 'pushNotificationActionPerformed', listenerFunc: (notification: ActionPerformed) => void) => Promise<PluginListenerHandle> & PluginListenerHandle
Called when an action is performed on a push notification.
Param | Type |
---|---|
eventName |
'pushNotificationActionPerformed' |
listenerFunc |
(notification: ActionPerformed) => void |
Returns: any
Since: 1.0.0
removeAllListeners() => any
Remove all native listeners for this plugin.
Returns: any
Since: 1.0.0
Prop | Type | Description | Since |
---|---|---|---|
notifications |
{} |
List of notifications that are visible on the notifications screen. | 1.0.0 |
Prop | Type | Description | Since |
---|---|---|---|
title |
string |
The notification title. | 1.0.0 |
subtitle |
string |
The notification subtitle. | 1.0.0 |
body |
string |
The main text payload for the notification. | 1.0.0 |
id |
string |
The notification identifier. | 1.0.0 |
tag |
string |
The notification tag. Only available on Android (from push notifications). | 4.0.0 |
badge |
number |
The number to display for the app icon badge. | 1.0.0 |
data |
any |
Any additional data that was included in the push notification payload. | 1.0.0 |
click_action |
string |
The action to be performed on the user opening the notification. Only available on Android. | 1.0.0 |
link |
string |
Deep link from the notification. Only available on Android. | 1.0.0 |
group |
string |
Set the group identifier for notification grouping. Only available on Android. Works like threadIdentifier on iOS. |
1.0.0 |
groupSummary |
boolean |
Designate this notification as the summary for an associated group . Only available on Android. |
1.0.0 |
Prop | Type | Description | Default | Since |
---|---|---|---|---|
id |
string |
The channel identifier. | 1.0.0 | |
name |
string |
The human-friendly name of this channel (presented to the user). | 1.0.0 | |
description |
string |
The description of this channel (presented to the user). | 1.0.0 | |
sound |
string |
The sound that should be played for notifications posted to this channel. Notification channels with an importance of at least 3 should have a sound. The file name of a sound file should be specified relative to the android app res/raw directory. |
1.0.0 | |
importance |
Importance |
The level of interruption for notifications posted to this channel. |
|
1.0.0 |
visibility |
Visibility |
The visibility of notifications posted to this channel. This setting is for whether notifications posted to this channel appear on the lockscreen or not, and if so, whether they appear in a redacted form. | 1.0.0 | |
lights |
boolean |
Whether notifications posted to this channel should display notification lights, on devices that support it. | 1.0.0 | |
lightColor |
string |
The light color for notifications posted to this channel. Only supported if lights are enabled on this channel and the device supports it. Supported color formats are #RRGGBB and #RRGGBBAA . |
1.0.0 | |
vibration |
boolean |
Whether notifications posted to this channel should vibrate. | 1.0.0 |
Prop | Type | Description | Since |
---|---|---|---|
channels |
{} |
List of all the Channels created by your app. | 1.0.0 |
Prop | Type | Description | Since |
---|---|---|---|
receive |
PermissionState |
Permission state of receiving notifications. | 1.0.0 |
Prop | Type | Description | Since |
---|---|---|---|
value |
string |
On iOS it contains the APNS token. On Android it contains the FCM token. | 1.0.0 |
Prop | Type |
---|---|
remove |
() => any |
Prop | Type | Description | Since |
---|---|---|---|
error |
string |
Error message describing the registration failure. | 1.0.0 |
Prop | Type | Description | Since |
---|---|---|---|
actionId |
string |
The action performed on the notification. | 1.0.0 |
inputValue |
string |
Text entered on the notification action. Only available on iOS. | 1.0.0 |
notification |
PushNotificationSchema |
The notification in which the action was performed. | 1.0.0 |
The importance level. For more details, see the Android Developer Docs
1 | 2 | 3 | 4 | 5
The notification visibility. For more details, see the Android Developer Docs
-1 | 0 | 1
'prompt' | 'prompt-with-rationale' | 'granted' | 'denied'