1.2.5 • Published 1 year ago

@jacotb/capacitor-firebase-messaging v1.2.5

Weekly downloads
-
License
Apache-2.0
Repository
github
Last release
1 year ago

@capacitor-firebase/messaging

⚡️ Capacitor plugin for Firebase Cloud Messaging (FCM).

Installation

npm install @capacitor-firebase/messaging firebase
npx cap sync

Add Firebase to your project if you haven't already (Android / iOS / Web).

Android

Variables

This plugin will use the following project variables (defined in your app’s variables.gradle file):

  • $firebaseMessagingVersion version of com.google.firebase:firebase-messaging (default: 20.0.6)

Push Notification Icon

The Push Notification icon with the appropriate name should be added to the android/app/src/main/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 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:

<meta-data
    android:name="firebase_messaging_auto_init_enabled"
    android:value="false" />
<meta-data
    android:name="firebase_analytics_collection_enabled"
    android:value="false" />

iOS

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. The steps are explained there in a quite understandable way. But be aware that this guide is more detailed and covers more than you need. Use it only for assistance.

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)
}
    
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)
}

Finally edit your ios/App/App/Info.plist and set FirebaseAppDelegateProxyEnabled key to NO.

Attention: If you use this plugin in combination with @capacitor-firebase/authentication, then add the following to your app's AppDelegate.swift:

+ 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.

Web

  1. See Configure Web Credentials with FCM and follow the instructions to configure your web credentials correctly.
  2. 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.

Configuration

On iOS you can configure the way the push notifications are displayed when the app is in foreground.

PropTypeDescriptionDefaultSince
presentationOptionsPresentationOption[]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. Only available for iOS."badge", "sound", "alert"0.2.2

Examples

In capacitor.config.json:

{
  "plugins": {
    "FirebaseMessaging": {
      "presentationOptions": ["badge", "sound", "alert"]
    }
  }
}

In capacitor.config.ts:

/// <reference types="@capacitor/firebase-messaging" />

import { CapacitorConfig } from '@capacitor/cli';

const config: CapacitorConfig = {
  plugins: {
    FirebaseMessaging: {
      presentationOptions: ["badge", "sound", "alert"],
    },
  },
};

export default config;

Demo

A working example can be found here: robingenz/capacitor-firebase-plugin-demo

Usage

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({
    ids: ['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();
};

API

checkPermissions()

checkPermissions() => Promise<PermissionStatus>

Check permission to receive push notifications.

Returns: Promise<PermissionStatus>

Since: 0.2.2


requestPermissions()

requestPermissions() => Promise<PermissionStatus>

Request permission to receive push notifications.

Returns: Promise<PermissionStatus>

Since: 0.2.2


isSupported()

isSupported() => Promise<IsSupportedResult>

Checks if all required APIs exist.

Always returns true on Android and iOS.

Returns: Promise<IsSupportedResult>

Since: 0.3.1


getToken(...)

getToken(options?: GetTokenOptions | undefined) => Promise<GetTokenResult>

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.

ParamType
optionsGetTokenOptions

Returns: Promise<GetTokenResult>

Since: 0.2.2


deleteToken()

deleteToken() => Promise<void>

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


getDeliveredNotifications()

getDeliveredNotifications() => Promise<GetDeliveredNotificationsResult>

Get a list of notifications that are visible on the notifications screen.

Returns: Promise<GetDeliveredNotificationsResult>

Since: 0.2.2


removeDeliveredNotifications(...)

removeDeliveredNotifications(options: RemoveDeliveredNotificationsOptions) => Promise<void>

Remove specific notifications from the notifications screen.

ParamType
optionsRemoveDeliveredNotificationsOptions

Since: 0.2.2


removeAllDeliveredNotifications()

removeAllDeliveredNotifications() => Promise<void>

Remove all notifications from the notifications screen.

Since: 0.2.2


subscribeToTopic(...)

subscribeToTopic(options: SubscribeToTopicOptions) => Promise<void>

Subscribes to topic in the background.

Only available for Android and iOS.

ParamType
optionsSubscribeToTopicOptions

Since: 0.2.2


unsubscribeFromTopic(...)

unsubscribeFromTopic(options: UnsubscribeFromTopicOptions) => Promise<void>

Unsubscribes from topic in the background.

Only available for Android and iOS.

ParamType
optionsUnsubscribeFromTopicOptions

Since: 0.2.2


addListener('tokenReceived', ...)

addListener(eventName: 'tokenReceived', listenerFunc: TokenReceivedListener) => Promise<PluginListenerHandle> & PluginListenerHandle

Called when a new FCM token is received.

ParamType
eventName'tokenReceived'
listenerFuncTokenReceivedListener

Returns: Promise<PluginListenerHandle> & PluginListenerHandle

Since: 0.2.2


addListener('notificationReceived', ...)

addListener(eventName: 'notificationReceived', listenerFunc: NotificationReceivedListener) => Promise<PluginListenerHandle> & PluginListenerHandle

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.

ParamType
eventName'notificationReceived'
listenerFuncNotificationReceivedListener

Returns: Promise<PluginListenerHandle> & PluginListenerHandle

Since: 0.2.2


addListener('notificationActionPerformed', ...)

addListener(eventName: 'notificationActionPerformed', listenerFunc: NotificationActionPerformedListener) => Promise<PluginListenerHandle> & PluginListenerHandle

Called when a new push notification action is performed.

Only available on Android and iOS.

ParamType
eventName'notificationActionPerformed'
listenerFuncNotificationActionPerformedListener

Returns: Promise<PluginListenerHandle> & PluginListenerHandle

Since: 0.2.2


removeAllListeners()

removeAllListeners() => Promise<void>

Remove all native listeners for this plugin.

Since: 0.2.2


Interfaces

PermissionStatus

PropTypeSince
receivePermissionState0.2.2

IsSupportedResult

PropTypeSince
isSupportedboolean0.3.1

GetTokenResult

PropTypeSince
tokenstring0.2.2

GetTokenOptions

PropTypeDescription
vapidKeystringYour VAPID public key, which is required to retrieve the current registration token on the web. Only available for Web.
serviceWorkerRegistrationServiceWorkerRegistrationThe 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

PropTypeSince
notificationsNotification[]0.2.2

Notification

PropTypeDescriptionSince
bodystringThe notification payload.0.2.2
clickActionstringThe action to be performed on the user opening the notification. Only available on Android.0.2.2
dataunknownAny additional data that was included in the push notification payload.0.2.2
idstringThe notification identifier.0.2.2
imagestringThe URL of an image that is downloaded on the device and displayed in the notification. Only available on Web.0.2.2
linkstringDeep link from the notification. Only available on Android.0.2.2
subtitlestringThe notification subtitle. Only available on iOS.0.2.2
tagstringThe notification string identifier. Only available on Android.0.4.0
titlestringThe notification title.0.2.2

RemoveDeliveredNotificationsOptions

PropTypeSince
notificationsNotification[]0.4.0

SubscribeToTopicOptions

PropTypeDescriptionSince
topicstringThe name of the topic to subscribe.0.2.2

UnsubscribeFromTopicOptions

PropTypeDescriptionSince
topicstringThe name of the topic to unsubscribe from.0.2.2

PluginListenerHandle

PropType
remove() => Promise<void>

TokenReceivedEvent

PropTypeSince
tokenstring0.2.2

NotificationReceivedEvent

PropTypeSince
notificationNotification0.2.2

NotificationActionPerformedEvent

PropTypeDescriptionSince
actionIdstringThe action performed on the notification.0.2.2
inputValuestringText entered on the notification action. Only available on iOS.0.2.2
notificationNotificationThe notification in which the action was performed.0.2.2

Type Aliases

PermissionState

'prompt' | 'prompt-with-rationale' | 'granted' | 'denied'

TokenReceivedListener

Callback to receive the push notification event.

(event: TokenReceivedEvent): void

NotificationReceivedListener

Callback to receive the push notification event.

(event: NotificationReceivedEvent): void

NotificationActionPerformedListener

Callback to receive the push notification event.

(event: NotificationActionPerformedEvent): void

Changelog

See CHANGELOG.md.

License

See LICENSE.

1.2.5

1 year ago

1.2.4

1 year ago

1.2.3

1 year ago

1.2.2

1 year ago

1.2.1

1 year ago