Capacitor plugin for Firebase Cloud Messaging (FCM).
npm install @capacitor-firebase/messagingUnofficial Capacitor plugin for Firebase Cloud Messaging.[^1]
- The Push Notifications Guide for Capacitor
| Plugin Version | Capacitor Version | Status |
| -------------- | ----------------- | -------------- |
| 8.x.x | >=8.x.x | Active support |
| 7.x.x | 7.x.x | Deprecated |
| 6.x.x | 6.x.x | Deprecated |
| 5.x.x | 5.x.x | Deprecated |
| 1.x.x | 4.x.x | Deprecated |
``bash`
npm install @capacitor-firebase/messaging firebase
npx cap sync
Add Firebase to your project if you haven't already (Android / iOS / Web).
#### Variables
If needed, you can define the following project variable in your app’s variables.gradle file to change the default version of the dependency:
- $firebaseMessagingVersion version of com.google.firebase:firebase-messaging (default: 25.0.1)
This can be useful if you encounter dependency conflicts with other plugins in your project.
#### Push Notification Icon
The Push Notification icon with the appropriate name should be added to the android/app/src/main/AndroidManifest.xml file:
`xml`
If no icon is specified, Android uses the application icon, but the push icon should be white pixels on a transparent background. Since the application icon does not usually look like this, it shows a white square or circle. Therefore, it is recommended to provide a separate icon for push notifications.
#### Prevent auto initialization
When a registration token is generated, the library uploads the identifier and configuration data to Firebase.
If you prefer to prevent token autogeneration, disable Analytics collection and FCM auto initialization by adding these metadata values to the android/app/src/main/AndroidManifest.xml file:
`xml`
android:value="false" />
android:value="false" />
> Important: Make sure that no other Capacitor Push Notification plugin is installed (see here).
See Prerequisites and complete the prerequisites first.
See Upload the APNS Certificate or Key to Firebase and follow the instructions to upload the APNS Certificate or APNS Auth Key to Firebase.
> If you have difficulties with the instructions, you can also look at the corresponding sections of this guide.
Add the following to your app's AppDelegate.swift:
`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)
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
NotificationCenter.default.post(name: Notification.Name.init("didReceiveRemoteNotification"), object: completionHandler, userInfo: userInfo)
}
`
Attention: If you use this plugin in combination with @capacitor-firebase/authentication, then add the following to your app's AppDelegate.swift:
`diff
+ import FirebaseAuth
func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
+ if Auth.auth().canHandle(url) {
+ return true
+ }
return ApplicationDelegateProxy.shared.application(app, open: url, options: options)
}
`
#### Prevent auto initialization
When a registration token is generated, the library uploads the identifier and configuration data to Firebase.
If you prefer to prevent token autogeneration, disable FCM auto initialization by editing your ios/App/App/Info.plist and set FirebaseMessagingAutoInitEnabled key to NO.
1. See Configure Web Credentials with FCM and follow the instructions to configure your web credentials correctly.
1. Add a firebase-messaging-sw.js file to the root of your domain. This file can be empty if you do not want to receive push notifications in the background.
See Setting notification options in the service worker for more information.
On iOS you can configure the way the push notifications are displayed when the app is in foreground.
| Prop | Type | Description | Default | 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 - criticalAlert: the push notification is displayed in a native dialog and bypasses the mute switch An empty array can be provided if none of the options are desired. Only available for iOS. | ["alert", "badge", "sound"] | 0.2.2 |
In capacitor.config.json:
`json`
{
"plugins": {
"FirebaseMessaging": {
"presentationOptions": ["alert", "badge", "sound"]
}
}
}
In capacitor.config.ts:
`ts
///
import { CapacitorConfig } from '@capacitor/cli';
const config: CapacitorConfig = {
plugins: {
FirebaseMessaging: {
presentationOptions: ["alert", "badge", "sound"],
},
},
};
export default config;
`
A working example can be found here: robingenz/capacitor-firebase-plugin-demo
The following starter templates are available:
`typescript
import { FirebaseMessaging } from '@capacitor-firebase/messaging';
const checkPermissions = async () => {
const result = await FirebaseMessaging.checkPermissions();
return result.receive;
};
const requestPermissions = async () => {
const result = await FirebaseMessaging.requestPermissions();
return result.receive;
};
const getToken = async () => {
const result = await FirebaseMessaging.getToken();
return result.token;
};
const deleteToken = async () => {
await FirebaseMessaging.deleteToken();
};
const getDeliveredNotifications = async () => {
const result = await FirebaseMessaging.getDeliveredNotifications();
return result.notifications;
};
const removeDeliveredNotifications = async () => {
await FirebaseMessaging.removeDeliveredNotifications({
notifications: [
{
id: '798dfhliblqew89pzads',
},
],
});
};
const removeAllDeliveredNotifications = async () => {
await FirebaseMessaging.removeAllDeliveredNotifications();
};
const subscribeToTopic = async () => {
await FirebaseMessaging.subscribeToTopic({ topic: 'news' });
};
const unsubscribeFromTopic = async () => {
await FirebaseMessaging.unsubscribeFromTopic({ topic: 'news' });
};
const addTokenReceivedListener = async () => {
await FirebaseMessaging.addListener('tokenReceived', event => {
console.log('tokenReceived', { event });
});
};
const addNotificationReceivedListener = async () => {
await FirebaseMessaging.addListener('notificationReceived', event => {
console.log('notificationReceived', { event });
});
};
const addNotificationActionPerformedListener = async () => {
await FirebaseMessaging.addListener('notificationActionPerformed', event => {
console.log('notificationActionPerformed', { event });
});
};
const removeAllListeners = async () => {
await FirebaseMessaging.removeAllListeners();
};
`
* checkPermissions()
* requestPermissions()
* isSupported()
* getToken(...)
* deleteToken()
* getDeliveredNotifications()
* removeDeliveredNotifications(...)
* removeAllDeliveredNotifications()
* subscribeToTopic(...)
* unsubscribeFromTopic(...)
* createChannel(...)
* deleteChannel(...)
* listChannels()
* addListener('tokenReceived', ...)
* addListener('notificationReceived', ...)
* addListener('notificationActionPerformed', ...)
* removeAllListeners()
* Interfaces
* Type Aliases
* Enums
`typescript`
checkPermissions() => Promise
Check permission to receive push notifications.
On Android, this method only needs to be called on Android 13+.
Returns: Promise<PermissionStatus>
Since: 0.2.2
--------------------
`typescript`
requestPermissions() => Promise
Request permission to receive push notifications.
On Android, this method only needs to be called on Android 13+.
Returns: Promise<PermissionStatus>
Since: 0.2.2
--------------------
`typescript`
isSupported() => Promise
Checks if all required APIs exist.
Always returns true on Android and iOS.
Returns: Promise<IsSupportedResult>
Since: 0.3.1
--------------------
`typescript`
getToken(options?: GetTokenOptions | undefined) => Promise
Register the app to receive push notifications.
Returns a FCM token that can be used to send push messages to that Messaging instance.
This method also re-enables FCM auto-init.
| Param | Type |
| ------------- | ----------------------------------------------------------- |
| options | GetTokenOptions |
Returns: Promise<GetTokenResult>
Since: 0.2.2
--------------------
`typescript`
deleteToken() => Promise
Delete the FCM token and unregister the app to stop receiving push notifications.
Can be called, for example, when a user signs out.
Since: 0.2.2
--------------------
`typescript`
getDeliveredNotifications() => Promise
Get a list of notifications that are visible on the notifications screen.
Note: This will return all delivered notifications, including local notifications, and not just FCM notifications.
On Android, the data field of the FCM notification will NOT be included.
Returns: Promise<GetDeliveredNotificationsResult>
Since: 0.2.2
--------------------
`typescript`
removeDeliveredNotifications(options: RemoveDeliveredNotificationsOptions) => Promise
Remove specific notifications from the notifications screen.
| Param | Type |
| ------------- | --------------------------------------------------------------------------------------------------- |
| options | RemoveDeliveredNotificationsOptions |
Since: 0.2.2
--------------------
`typescript`
removeAllDeliveredNotifications() => Promise
Remove all notifications from the notifications screen.
Note: This will remove all delivered notifications, including local notifications, and not just FCM notifications.
Since: 0.2.2
--------------------
`typescript`
subscribeToTopic(options: SubscribeToTopicOptions) => Promise
Subscribes to topic in the background.
Only available for Android and iOS.
| Param | Type |
| ------------- | --------------------------------------------------------------------------- |
| options | SubscribeToTopicOptions |
Since: 0.2.2
--------------------
`typescript`
unsubscribeFromTopic(options: UnsubscribeFromTopicOptions) => Promise
Unsubscribes from topic in the background.
Only available for Android and iOS.
| Param | Type |
| ------------- | ----------------------------------------------------------------------------------- |
| options | UnsubscribeFromTopicOptions |
Since: 0.2.2
--------------------
`typescript`
createChannel(options: CreateChannelOptions) => Promise
Create a notification channel.
Only available for Android (SDK 26+).
| Param | Type |
| ------------- | ------------------------------------------- |
| options | Channel |
Since: 1.4.0
--------------------
`typescript`
deleteChannel(options: DeleteChannelOptions) => Promise
Delete a notification channel.
Only available for Android (SDK 26+).
| Param | Type |
| ------------- | --------------------------------------------------------------------- |
| options | DeleteChannelOptions |
Since: 1.4.0
--------------------
`typescript`
listChannels() => Promise
List the available notification channels.
Only available for Android (SDK 26+).
Returns: Promise<ListChannelsResult>
Since: 1.4.0
--------------------
`typescript`
addListener(eventName: 'tokenReceived', listenerFunc: TokenReceivedListener) => Promise
Called when a new FCM token is received.
Only available for Android and iOS.
| Param | Type |
| ------------------ | ----------------------------------------------------------------------- |
| eventName | 'tokenReceived' |
| listenerFunc | TokenReceivedListener |
Returns: Promise<PluginListenerHandle>
Since: 0.2.2
--------------------
`typescript`
addListener(eventName: 'notificationReceived', listenerFunc: NotificationReceivedListener) => Promise
Called when a new push notification is received.
On Android, this listener is called for every push notification if the app is in the _foreground_.
If the app is in the _background_, then this listener is only called on data push notifications.
See https://firebase.google.com/docs/cloud-messaging/android/receive#handling_messages for more information.
On iOS, this listener is called for every push notification if the app is in the _foreground_.
If the app is in the _background_, then this listener is only called for silent push notifications (messages with the content-available key).
See https://developer.apple.com/library/archive/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/PayloadKeyReference.html for more information.
| Param | Type |
| ------------------ | ------------------------------------------------------------------------------------- |
| eventName | 'notificationReceived' |
| listenerFunc | NotificationReceivedListener |
Returns: Promise<PluginListenerHandle>
Since: 0.2.2
--------------------
`typescript`
addListener(eventName: 'notificationActionPerformed', listenerFunc: NotificationActionPerformedListener) => Promise
Called when a new push notification action is performed.
Only available for Android and iOS.
| Param | Type |
| ------------------ | --------------------------------------------------------------------------------------------------- |
| eventName | 'notificationActionPerformed' |
| listenerFunc | NotificationActionPerformedListener |
Returns: Promise<PluginListenerHandle>
Since: 0.2.2
--------------------
`typescript`
removeAllListeners() => Promise
Remove all listeners for this plugin.
Since: 0.2.2
--------------------
#### PermissionStatus
| Prop | Type | Since |
| ------------- | ----------------------------------------------------------- | ----- |
| receive | PermissionState | 0.2.2 |
#### IsSupportedResult
| Prop | Type | Since |
| ----------------- | -------------------- | ----- |
| isSupported | boolean | 0.3.1 |
#### GetTokenResult
| Prop | Type | Since |
| ----------- | ------------------- | ----- |
| token | string | 0.2.2 |
#### GetTokenOptions
| Prop | Type | Description |
| ------------------------------- | -------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| vapidKey | string | Your VAPID public key, which is required to retrieve the current registration token on the web. Only available for Web. |
| serviceWorkerRegistration | ServiceWorkerRegistration | The service worker registration for receiving push messaging. If the registration is not provided explicitly, you need to have a firebase-messaging-sw.js at your root location. Only available for Web. |
#### GetDeliveredNotificationsResult
| Prop | Type | Since |
| ------------------- | --------------------------- | ----- |
| notifications | Notification[] | 0.2.2 |
#### Notification
| Prop | Type | Description | Since |
| ----------------- | -------------------- | --------------------------------------------------------------------------------------------------------------- | ----- |
| body | string | The notification payload. | 0.2.2 |
| clickAction | string | The action to be performed on the user opening the notification. Only available for Android. | 0.2.2 |
| data | unknown | Any additional data that was included in the push notification payload. | 0.2.2 |
| id | string | The notification identifier. | 0.2.2 |
| image | string | The URL of an image that is downloaded on the device and displayed in the notification. Only available for Web. | 0.2.2 |
| link | string | Deep link from the notification. Only available for Android. | 0.2.2 |
| subtitle | string | The notification subtitle. Only available for iOS. | 0.2.2 |
| tag | string | The notification string identifier. Only available for Android. | 0.4.0 |
| title | string | The notification title. | 0.2.2 |
#### RemoveDeliveredNotificationsOptions
| Prop | Type | Since |
| ------------------- | --------------------------- | ----- |
| notifications | Notification[] | 0.4.0 |
#### SubscribeToTopicOptions
| Prop | Type | Description | Since |
| ----------- | ------------------- | ----------------------------------- | ----- |
| topic | string | The name of the topic to subscribe. | 0.2.2 |
#### UnsubscribeFromTopicOptions
| Prop | Type | Description | Since |
| ----------- | ------------------- | ------------------------------------------ | ----- |
| topic | string | The name of the topic to unsubscribe from. | 0.2.2 |
#### Channel
| Prop | Type | Description | Since |
| ----------------- | ------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----- |
| description | string | The description of this channel (presented to the user). | 1.4.0 |
| id | string | The channel identifier. | 1.4.0 |
| importance | Importance | The level of interruption for notifications posted to this channel. | 1.4.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.4.0 |lights
| | nameboolean | Whether notifications posted to this channel should display notification lights, on devices that support it. | 1.4.0 |
| | soundstring | The name of this channel (presented to the user). | 1.4.0 |
| | 3string | The sound that should be played for notifications posted to this channel. Notification channels with an importance of at least should have a sound. The file name of a sound file should be specified relative to the android app res/raw directory. | 1.4.0 |vibration
| | visibilityboolean | Whether notifications posted to this channel should vibrate. | 1.4.0 |
| | 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.4.0 |
#### DeleteChannelOptions
| Prop | Type | Description | Since |
| -------- | ------------------- | ----------------------- | ----- |
| id | string | The channel identifier. | 1.4.0 |
#### ListChannelsResult
| Prop | Type |
| -------------- | ---------------------- |
| channels | Channel[] |
#### PluginListenerHandle
| Prop | Type |
| ------------ | ----------------------------------------- |
| remove | () => Promise<void> |
#### TokenReceivedEvent
| Prop | Type | Since |
| ----------- | ------------------- | ----- |
| token | string | 0.2.2 |
#### NotificationReceivedEvent
| Prop | Type | Since |
| ------------------ | ----------------------------------------------------- | ----- |
| notification | Notification | 0.2.2 |
#### NotificationActionPerformedEvent
| Prop | Type | Description | Since |
| ------------------ | ----------------------------------------------------- | ---------------------------------------------------------------- | ----- |
| actionId | string | The action performed on the notification. | 0.2.2 |
| inputValue | string | Text entered on the notification action. Only available for iOS. | 0.2.2 |
| notification | Notification | The notification in which the action was performed. | 0.2.2 |
#### PermissionState
'prompt' | 'prompt-with-rationale' | 'granted' | 'denied'
#### CreateChannelOptions
#### TokenReceivedListener
Callback to receive the token received event.
(event: TokenReceivedEvent): void
#### NotificationReceivedListener
Callback to receive the notification received event.
(event: NotificationReceivedEvent): void
#### NotificationActionPerformedListener
Callback to receive the notification action performed event.
(event: NotificationActionPerformedEvent): void
#### Importance
| Members | Value | Since |
| ------------- | -------------- | ----- |
| Min | 1 | 1.4.0 |
| Low | 2 | 1.4.0 |
| Default | 3 | 1.4.0 |
| High | 4 | 1.4.0 |
| Max | 5 | 1.4.0 |
#### Visibility
| Members | Value | Since |
| ------------- | --------------- | ----- |
| Secret | -1 | 1.4.0 |
| Private | 0 | 1.4.0 |
| Public` | 1 | 1.4.0 |
See CHANGELOG.md.
See LICENSE.
[^1]: This project is not affiliated with, endorsed by, sponsored by, or approved by Google LLC or any of their affiliates or subsidiaries.