Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

cordova-plugin-fcm-with-dependecy-updated

andrehtissot2.1kMIT7.8.0TypeScript support: included

Google Firebase Cloud Messaging Cordova Push Plugin fork with dependecy updated

ecosystem:cordova, cordova-android, cordova-ios, notifications, push, firebase, fcm, ios, android, cordova

readme

Google Firebase Cloud Messaging Cordova Push Plugin

Extremely easy plug&play push notification plugin for Cordova applications with Google Firebase FCM.

Donate npm downloads npm per month npm version License: MIT GitHub issues GitHub forks GitHub stars Known Vulnerabilities DeepScan grade

How it works | Installation | Push Payload Configuration | Features | Example Apps | Companion Plugins | Changelog | Authorship

How it works

Send a push notification to a single device or topic.

  • Application is in foreground:

    • The notification data is received in the JavaScript callback without notification bar message (this is the normal behavior of mobile push notifications).
    • For Android, to show the notification received on the foreground, it's recommended to use cordova-plugin-local-notification as it provides many presentation and interaction features.
  • Application is in background or closed:

    • The device displays the notification message in the device notification bar.
    • If the user taps the notification, the application comes to foreground and the notification data is received in the JavaScript callback.
    • If the user does not tap the notification but opens the application, nothing happens until the notification is tapped.

Push Notifications on iOS

On Android, push notifications don't require any special permission and can be tested from emulators freely.

Unfortunately, Apple is not as nice to work with, requiring:

  • The running device to be a real device, no simulators allowed;
  • Application has require the UIBackgroundModes=[remote-notification] permission (automatically configured by this plugin);
  • The user running the application has to manually allow the application to receive push notifications;
  • The application must be build with credentials created from a paid account (or team) that is allowed to receive push notifications;
  • The build installed has to have come from either Apple Store or TestFlight; Or, be build with a special certificate (https://customersupport.doubledutch.me/hc/en-us/articles/229495568-iOS-How-to-Create-a-Push-Notification-Certificate)

Installation

Make sure you have ‘google-services.json’ for Android and/or ‘GoogleService-Info.plist’ for iOS in your Cordova project root folder.

Preferences

Preference Default Value Description
ANDROID_DEFAULT_NOTIFICATION_ICON @mipmap/ic_launcher Default notification icon.
ANDROID_FCM_VERSION 21.0.0 Native Firebase Message SDK version.
:warning: Replaced by BoM versioning on Gradle >= 3.4.
ANDROID_FIREBASE_BOM_VERSION 26.0.0 Firebase BoM version.
ANDROID_GOOGLE_SERVICES_VERSION 4.3.4 Native Google Services SDK version.
ANDROID_GRADLE_TOOLS_VERSION 4.1.0 Gradle tools version.
IOS_FIREBASE_MESSAGING_VERSION ~> 7.4.0 Native Firebase Message SDK version

Cordova

Default preferences:

npm install -g cordova@latest # Version 9 or higher required
npm uninstall @ionic-native/fcm # Ionic support is included and conflicts with @ionic-native's implementation.
cordova plugin add cordova-plugin-fcm-with-dependecy-updated

Complete:

npm install -g cordova@latest # Version 9 or higher required
npm uninstall @ionic-native/fcm # Ionic support is included and conflicts with @ionic-native's implementation.
cordova plugin add cordova-plugin-fcm-with-dependecy-updated \
  --variable ANDROID_DEFAULT_NOTIFICATION_ICON="@mipmap/ic_launcher" \
  --variable ANDROID_FIREBASE_BOM_VERSION="26.0.0" \
  --variable ANDROID_GOOGLE_SERVICES_VERSION="4.3.4" \
  --variable ANDROID_GRADLE_TOOLS_VERSION="4.1.0" \
  --variable IOS_FIREBASE_MESSAGING_VERSION="~> 7.4.0"

Ionic

Default preferences:

npm install -g cordova@latest # Version 9 or higher required
npm uninstall @ionic-native/fcm # Ionic support is included and conflicts with @ionic-native's implementation.
ionic cordova plugin add cordova-plugin-fcm-with-dependecy-updated

Complete:

npm install -g cordova@latest # Version 9 or higher required
npm uninstall @ionic-native/fcm # Ionic support is included and conflicts with @ionic-native's implementation.
ionic cordova plugin add cordova-plugin-fcm-with-dependecy-updated \
  --variable ANDROID_DEFAULT_NOTIFICATION_ICON="@mipmap/ic_launcher" \
  --variable ANDROID_FIREBASE_BOM_VERSION="26.0.0" \
  --variable ANDROID_GOOGLE_SERVICES_VERSION="4.3.4" \
  --variable ANDROID_GRADLE_TOOLS_VERSION="4.1.0" \
  --variable IOS_FIREBASE_MESSAGING_VERSION="~> 7.4.0"

Push Payload Configuration

Besides common FCM configuration (https://firebase.google.com/docs/cloud-messaging/ios/certs), the Push payload should contain "notification" and "data" keys and "click_action" equals to "FCM_PLUGIN_ACTIVITY" within "notification".

Structure expected:

{
  ...,
  "notification": {
    ...
  },
  "data": {
    ...
  },
  "android": {
    "notification": {
      "click_action": "FCM_PLUGIN_ACTIVITY"
    }
  },
  ...,
}

Example:

{
  "token": "[FCM token]",
  "notification":{
    "title":"Notification title",
    "body":"Notification body",
    "sound":"default",
  },
  "data":{
    "param1":"value1",
    "param2":"value2"
  },
  "android": {
    "notification": {
      "icon":"fcm_push_icon",
      "click_action": "FCM_PLUGIN_ACTIVITY"
    }
  }
}

Features

As its own

The JS functions are now as written bellow and do require Promise support. Which, for Android API 19 support, it can be fulfilled by a polyfill.

FCM.clearAllNotifications()

Removes existing push notifications from the notifications center.

await FCM.clearAllNotifications();
FCM.createNotificationChannel()

For Android, some notification properties are only defined programmatically. Channel can define the default behavior for notifications on Android 8.0+. Once a channel is created, it stays unchangeable until the user uninstalls the app.

await FCM.createNotificationChannel({
  id: "urgent_alert", // required
  name: "Urgent Alert", // required
  description: "Very urgent message alert",
  importance: "high", // https://developer.android.com/guide/topics/ui/notifiers/notifications#importance
  visibility: "public", // https://developer.android.com/training/notify-user/build-notification#lockscreenNotification
  sound: "alert_sound", // In the "alert_sound" example, the file should located as resources/raw/alert_sound.mp3
  lights: true, // enable lights for notifications
  vibration: true // enable vibration for notifications
});
FCM.deleteInstanceId()

Deletes the InstanceId, revoking all tokens.

await FCM.deleteInstanceId();
FCM.getAPNSToken()

Gets iOS device's current APNS token.

const apnsToken: string = await FCM.getAPNSToken();
FCM.getInitialPushPayload()

Retrieves the message that, on tap, opened the app. And null, if the app was open normally.

const pushPayload: object = await FCM.getInitialPushPayload()
FCM.getToken()

Gets device's current registration id.

const fcmToken: string = await FCM.getToken()
FCM.hasPermission()

Checking for permissions on iOS. On android, it always returns true.

const doesIt: boolean = await FCM.hasPermission()
FCM.onNotification()

Callback firing when receiving new notifications. It serves as a shortcut to listen to eventTarget's "notification" event.

const disposable = FCM.onNotification((payload: object) => {
  // ...
})
// ...
disposable.dispose() // To remove listener

:warning: If the subscription to notification events happens after the notification has been fired, it'll be lost. As it is expected that you'd not always be able to catch the notification payload that the opened the app, the FCM.getInitialPushPayload() method was introduced.

FCM.onTokenRefresh()

Callback firing when receiving a new Firebase token. It serves as a shortcut to listen to eventTarget's "tokenRefresh" event.

const disposable = FCM.onTokenRefresh((fcmToken: string) => {
  // ...
})
// ...
disposable.dispose() // To remove listener
FCM.requestPushPermission()

Request push notification permission on iOS, alerting the user if he/she/they have not yet accepted or denied. For Android, it'll always return true.

const wasPermissionGiven: boolean = await FCM.requestPushPermission({
  ios9Support: {
    timeout: 10,  // How long it will wait for a decision from the user before returning `false`
    interval: 0.3 // How long between each permission verification
  }
})

:warning: Without this request, the Application won't receive any notification on iOS! :warning: The user will only have its permition required once, after that time, this call will only return if the permission was given that time.

FCM.subscribeToTopic()

Subscribes you to a topic.

const topic: string
// ...
await FCM.subscribeToTopic(topic)
FCM.unsubscribeFromTopic()

Unsubscribes you from a topic.

const topic: string
// ...
await FCM.unsubscribeFromTopic(topic)
FCM.eventTarget

EventTarget object for native-sourced custom events. Useful for more advanced listening handling.

const listener = (data) => {
  const payload = data.detail
  // ...
}
FCM.eventTarget.addEventListener("notification", listener, false);
// ...
FCM.eventTarget.removeEventListener("notification", listener, false);

With Ionic

Ionic support was implemented as part of this plugin to allow users to have access to newer features with the type support. It is available in 3 flavors:

  • Ionic v5:
    import { FCM } from "cordova-plugin-fcm-with-dependecy-updated/ionic";
  • Ionic ngx:
    import { FCM } from "cordova-plugin-fcm-with-dependecy-updated/ionic/ngx";
  • Ionic v4 (also works for Ionic v3):
    import { FCM } from "cordova-plugin-fcm-with-dependecy-updated/ionic/v4";

It brings the same behavior as the native implementation, except for FCM.onNotification() and FCM.onTokenRefresh(), which gain rxjs' Observable support.

To avoid confusion, it's suggested to also remove the redundant @ionic-native/fcm package.

FCM.onNotification()

Event firing when receiving new notifications.

this.fcm.onNotification().subscribe((payload: object) => {
  // ...
});
FCM.onTokenRefresh()

Event firing when receiving a new Firebase token.

this.fcm.onTokenRefresh().subscribe((token: string) => {
  // ...
});

Example Apps

Cordova

https://github.com/andrehtissot/cordova-plugin-fcm-with-dependecy-updated-app-example

Ionic v3

https://github.com/andrehtissot/cordova-plugin-fcm-with-dependecy-updated-ionic-v3-example

Ionic v5

https://github.com/andrehtissot/cordova-plugin-fcm-with-dependecy-updated-ionic-v5-example

Companion Plugins

Optional standalone FCM Image Support for Cordova iOS

After a lot of work, the first release of the plugin is out. Which should enable the support, just by installing it.

Link: https://github.com/andrehtissot/cordova-plugin-fcm-image-support

Optional standalone Cocoapods CDN source switcher

When the environment supports, the cocoapods source is automatically set to the official CDN instead of the slow Github repository.

Link: https://github.com/andrehtissot/cordova-plugin-cocoapods-cdn

Authorship

This started as a fork from https://github.com/fechanique/cordova-plugin-fcm and, gradually, had most of its implementation rewritten and improved, for newer dependency versions support, jitpack and cocoapods support, and new useful features.

changelog

Changelog

Version 7

Version 7.8.0 (03/02/2020)

  • IOS_FIREBASE_MESSAGING_VERSION upgraded to 7.4.0;
  • FCM.hasPermission now supports Android;
  • On iOS, getToken will now wait until fcm token is defined to return it;
  • FCM.getInitialPushPayload now uses UTF8 instead of ISOLatin;

Version 7.7.0 (11/12/2020)

Downgraded Cordova and Cordova-Android minimal required versions.

Version 7.6.1 (11/12/2020)

Fixed auto install of ionic-specific dependencies on Windows

Version 7.6.0 (08/11/2020)

Added IOS_FIREBASE_MESSAGING_VERSION plugin variable to force a fixed Firebase/Messaging pod version.

Version 7.5.0 (08/11/2020)

For pure Cordova projects, ionic dependencies are skipped for "ionic", "ionic/ngx" and "ionic/v4".

Version 7.4.0 (01/11/2020)

Upgraded Android and Node depenencies.

Version 7.3.1 (06/09/2020)

Android: Avoided setting initialPushPayload from a non-tapped notification.

Version 7.3.0 (30/08/2020)

Removed optional Firebase/Analytics iOS dependency.

Version 7.2.0 (23/08/2020)

Added deleteInstanceId to allow user's "resetting" Firebase session (https://firebase.google.com/support/privacy/manage-iids#delete_an_instance_id).

Version 7.1.1 (16/08/2020)

iOS: Values sent as notification on push payload should never overwrite values sent as data.

Android: tapping action small refactor.

Ionic: Removed tslib dependency due to reported incompatibility.

Version 7.1.0 (16/08/2020)

For iOS: Added title, subtitle, body and badge to the data given to JS.

This data is coming from notification part of the push payload, instead of only from data.

Android has been responding this way for a long time with title and body.

Version 7.0.10 (16/08/2020)

Defined minimal version of "cordova" package supported as version 9. Due to issues of supporting lower versions and "cordova-ios@5+" without deprecated configuration.

Removed explicit definition of "Firebase/Analytics" and "Firebase/Messaging" due to lack of matching “>=” definitions between plugins.

Version 7.0.9 (21/07/2020)

getInitialPushPayload: Conversion of NSData* into NSDictonary* fix -- Thanks to @medeirosrafael for debugging and fixing it!

Version 7.0.8 (20/07/2020)

Avoided execution of install_ionic_dependencies.bat after the app is installed;

Removed old framework dependencies -- Thanks for @QuentinFarizon, for pointing it out!

Version 7.0.7 (17/07/2020)

Removed auto-cdnfy due to service issues;

Set AndroidXEnabled for cordova-android-9.0.0 (https://cordova.apache.org/announcements/2020/06/29/cordova-android-9.0.0.html).

Version 7.0.6 (14/07/2020)

Simplified ionic/ngx/FCM.d.ts imports

Version 7.0.5 (13/07/2020)

Renamed extension scripts/install_ionic_dependencies.sh to .bat, to have it running on windows.

Version 7.0.4 (13/07/2020)

Simplified ionic/FCM.js and ionic/ngx/FCM.js files to ease building with them.

Improved scripts/install_ionic_dependencies.sh windows support.

Version 7.0.3 (07/07/2020)

Simplified ionic/v4/FCM.js file by setting the FCM function in the global context.

Version 7.0.2 (01/07/2020)

Simplified .d.ts files by removing the new "type" from imports and exports.

Version 7.0.1 (28/06/2020)

Replaced native to JS context messaging, from JS injection to event subscription.

Version 7.0.0 (27/06/2020)

Breaking update released. Please pay atention to the changes in plugin preferences and API methods.

Version 6

Version 6.4.0 (21/05/2020)

The FCMPlugin.requestPushPermissionIOS function now, not only triggers the request alert, but also returns, as boolean, if the permission was given.

FCMPlugin.requestPushPermissionIOS(
  function(wasPermissionGiven) {
    console.info("Was permission given: "+wasPermissionGiven);
  },
  function(error) {
    console.error(error);
  },
  ios9Support: {
    timeout: 10,  // How long it will wait for a decision from the user before returning `false`
    interval: 0.3 // How long between each permission verification
  }
);

Note: On iOS 9, there is no way to know if the user has denied the permissions or he has not yet decided. For this reason, specifically for iOS 9, after presenting the alert, a timed loop waits until it knows that the user has either given the permissions or that the time has expired. On iOS 10+, the return is given as soon as the user has selected, ignoring these options.

Version 6.3.0 (27/04/2020)

FCMPlugin.createNotificationChannelAndroid improved, now accepting three other options: "sound", "lights" and "vibration", like in:

FCMPlugin.createNotificationChannelAndroid({
  id: "urgent_alert", // required
  name: "Urgent Alert", // required
  description: "Very urgent message alert",
  importance: "high", // https://developer.android.com/guide/topics/ui/notifiers/notifications#importance
  visibility: "public", // https://developer.android.com/training/notify-user/build-notification#lockscreenNotification
  sound: "alert_sound", // In the "alert_sound" example, the file should located as resources/raw/alert_sound.mp3
  lights: true, // enable lights for notifications
  vibration: true // enable vibration for notifications
});

Version 6.2.0 (26/04/2020)

IOS 9 support reintroduced.

Version 6.1.0 (24/04/2020)

For Android, some notification properties are only defined programmatically, one of those is channel. Channel can define the default behavior for notifications on Android 8.0+. This feature was meant to bring the channel-only configurations importance and visibility:

FCMPlugin.createNotificationChannelAndroid({
  id: "urgent_alert", // required
  name: "Urgent Alert", // required
  description: "Very urgent message alert",
  importance: "high", // https://developer.android.com/guide/topics/ui/notifiers/notifications#importance
  visibility: "public", // https://developer.android.com/training/notify-user/build-notification#lockscreenNotification 
});

:warning: Once a channel is created, it stays unchangeable until the user uninstalls the app.

To have a notification to use the channel, you have to add to the push notification payload the key android_channel_id with the id given to createNotificationChannelAndroid (https://firebase.google.com/docs/cloud-messaging/http-server-ref#notification-payload-support)

Version 6.0.1 (20/04/2020)

As a hotfix to avoid incompatibility with cordova-plugin-ionic-webview, the the changes requested for cordova support (https://cordova.apache.org/howto/2020/03/18/wkwebviewonly) will not be automatic applied.

Version 6.0.0 (18/04/2020)

On iOS, first run doesn't automatically request Push permission.

The permission, as it is still required, may now be requested from javascript at any moment by executing:

//FCMPlugin.requestPushPermissionIOS( successCallback(), errorCallback(err) );
FCMPlugin.requestPushPermissionIOS();

Version 5

Minor changes omitted.

Version 5.1.0 (18/04/2020)

Replaced UIWebView with WKWebView, as required by Apple (https://developer.apple.com/documentation/uikit/uiwebview).

For a smooth upgrade, the changes requested for cordova support (https://cordova.apache.org/howto/2020/03/18/wkwebviewonly) are applied automatically.

Version 5.0.0 (16/04/2020)

For both platforms:

  • Not only copies, from application root, the Google Services configuration files on build, but also on install;
  • onFirebaseDataNotificationIOS removed, as relied on upstream socket connection, which will is deprecated and will be removed in Firebase 7 (https://firebase.google.com/support/release-notes/ios#fcm, announced in February 25, 2020).

For iOS:

  • On install "Remote Notification" is set as a "Background Mode" capacity automatically;
  • Firebase now is handled manually, due to complications of auto-swizzling;
  • Firebase dependencies are now set to 6.21.0;
  • Delayed Firebase registration, by 300ms, to avoid deadlock issue with Watchdog;
  • Removed support for iOS 9.

For Android:

  • Demonstrative code, for custom notifications, was removed and its imports of androidx classes to improve compatibility with older cordova plugins.

Version 4

Minor changes omitted.

Version 4.6.0 (04/04/2020)

For the IOS, if app is on the foreground and the app receives a data push notification, the data can be retrieved by setting the callback to the new method: FCMPlugin.onFirebaseDataNotificationIOS [Deprecated].

FCMPlugin.onFirebaseDataNotificationIOS(
  function(payload) {
    console.info("Message id: "+payload.messageID)
    console.info("Data parameters: "+payload.appData)
  }
);

This method is specifically implemented on IOS due to specific payload format (src/FCMPlugin.d.ts).

Version 4.5.1 (30/03/2020)

Due to a bug introduced in v4.4.3, the file platforms/android/app/src/main/res/values/strings.xml had two tags included on install, tags which, on build, are also included by cordova-android@8.x.x. Hence failing the build process.

To apply the fix, install the new version and remove these two tags from your values/strings.xml:

  • <string name="google_app_id">...</string>
  • <string name="google_api_key">...</string>

Version 4.2.0 (24/02/2020)

ANDROID_DEFAULT_NOTIFICATION_ICON included as a variable.

To define the default icon for notifications (com.google.firebase.messaging.default_notification_icon), install this plugin like:

cordova plugin add cordova-plugin-fcm-with-dependecy-updated --variable ANDROID_DEFAULT_NOTIFICATION_ICON="@mipmap/notification_icon"

Version 4.1.0 (26/10/2019)

Older notifications can be cleared from notification center. Works on both IOS and Android.

//FCMPlugin.clearAllNotifications( successCallback(msg), errorCallback(err) );
FCMPlugin.clearAllNotifications();

Version 4.0.0 (12/10/2019)

The old FCMPlugin.getToken is focused on retrieving the FCM Token. For the IOS, APNS token can now be retrieved by the new method:

FCMPlugin.getAPNSToken(
  function(token) {
    console.info("Retrieved token: "+token)
  },
  function(error) {
    console.error(error);
  }
);

On android, it will always return null.

The APNS token, once given, should not change for the same user (as commented on in https://stackoverflow.com/questions/6652242/does-the-apns-device-token-ever-change-once-created).

Although, contrary to APNS, the FCM tokens do expire, and for this reason, FCMPlugin.onTokenRefresh will be called with the new one FCM token.

Version 3

Minor changes omitted.

Version 3.2.0 (16/09/2019)

Checking for permissions

Useful for IOS. On android, it will always return true.

FCMPlugin.hasPermission(function(doesIt){
    // doesIt === true => yes, push was allowed
    // doesIt === false => nope, push will not be available
    // doesIt === null => still not answered, recommended checking again later
    if(doesIt) {
        haveFun();
    }
});

Version 2

Minor changes omitted.

Version 2.1.2 (03/06/2017)

  • Tested on Android and iOS using Cordova cli 6.4.0, Cordova android 6.0.0 and Cordova ios 4.3.1
  • Available sdk functions: onTokenRefresh, getToken, subscribeToTopic, unsubscribeFromTopic and onNotification
  • 'google-services.json' and 'GoogleService-Info.plist' are added automatically from Cordova project root to platform folders
  • Added data payload parameter to check whether the user tapped on the notification or was received while in foreground.
  • Free testing server available for free! https://cordova-plugin-fcm.appspot.com