@capacitor/push-notifications
The Push Notifications API provides access to native push notifications.
Install
npm install @capacitor/push-notifications
npx cap sync
iOS
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)
}
Android
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.
Variables
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
)
Push Notifications icon
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.
Push notifications appearance in foreground
You can configure the way the push notifications are displayed when the app is in foreground.
Prop | Type | Description | Since |
---|---|---|---|
presentationOptions | PresentationOption[] | 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 |
Examples
In capacitor.config.json
:
{
"plugins": {
"PushNotifications": {
"presentationOptions": ["badge", "sound", "alert"]
}
}
}
In capacitor.config.ts
:
/// <reference types="@capacitor/push-notifications" />
import { CapacitorConfig } from '@capacitor/cli';
const config: CapacitorConfig = {
plugins: {
PushNotifications: {
presentationOptions: ["badge", "sound", "alert"],
},
},
};
export default config;
Silent Push Notifications / Data-only Notifications
iOS
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.
Android
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.
Common Issues
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.
Example
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);
}
API
register()
getDeliveredNotifications()
removeDeliveredNotifications(...)
removeAllDeliveredNotifications()
createChannel(...)
deleteChannel(...)
listChannels()
checkPermissions()
requestPermissions()
addListener('registration', ...)
addListener('registrationError', ...)
addListener('pushNotificationReceived', ...)
addListener('pushNotificationActionPerformed', ...)
removeAllListeners()
- Interfaces
- Type Aliases
register()
register() => Promise<void>
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.
Since: 1.0.0
getDeliveredNotifications()
getDeliveredNotifications() => Promise<DeliveredNotifications>
Get a list of notifications that are visible on the notifications screen.
Returns:
Promise<DeliveredNotifications>
Since: 1.0.0
removeDeliveredNotifications(...)
removeDeliveredNotifications(delivered: DeliveredNotifications) => Promise<void>
Remove the specified notifications from the notifications screen.
Param | Type |
---|---|
delivered |
|
Since: 1.0.0
removeAllDeliveredNotifications()
removeAllDeliveredNotifications() => Promise<void>
Remove all the notifications from the notifications screen.
Since: 1.0.0
createChannel(...)
createChannel(channel: Channel) => Promise<void>
Create a notification channel.
Only available on Android O or newer (SDK 26+).
Param | Type |
---|---|
channel |
|
Since: 1.0.0
deleteChannel(...)
deleteChannel(args: { id: string; }) => Promise<void>
Delete a notification channel.
Only available on Android O or newer (SDK 26+).
Param | Type |
---|---|
args | { id: string; } |
Since: 1.0.0
listChannels()
listChannels() => Promise<ListChannelsResult>
List the available notification channels.
Only available on Android O or newer (SDK 26+).
Returns:
Promise<ListChannelsResult>
Since: 1.0.0
checkPermissions()
checkPermissions() => Promise<PermissionStatus>
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:
Promise<PermissionStatus>
Since: 1.0.0
requestPermissions()
requestPermissions() => Promise<PermissionStatus>
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:
Promise<PermissionStatus>
Since: 1.0.0
addListener('registration', ...)
addListener(eventName: 'registration', listenerFunc: (token: Token) => void) => Promise<PluginListenerHandle> & PluginListenerHandle