cordova-plugin-firebasex
Version:
Backward-compatible wrapper that installs all cordova-plugin-firebasex modular plugins
788 lines (633 loc) • 232 kB
Markdown
# cordova-plugin-firebasex [](https://www.npmjs.com/package/cordova-plugin-firebasex) [](https://npm-stat.com/charts.html?package=cordova-plugin-firebasex)
Brings push notifications, analytics, event tracking, crash reporting and more from Google Firebase to your Cordova project.
Supported platforms: Android and iOS
**IMPORTANT:** Before opening an issue against this plugin, please read [Reporting issues](#reporting-issues).
<!-- DONATE -->
[](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=ZRD3W47HQ3EMJ)
I dedicate a considerable amount of my free time to developing and maintaining this Cordova plugin, along with my other Open Source software.
To help ensure this plugin is kept updated, new features are added and bugfixes are implemented quickly, please donate a couple of dollars (or a little more if you can stretch) as this will help me to afford to dedicate time to its maintenance. Please consider donating if you're using this plugin in an app that makes you money, if you're being paid to make the app, if you're asking for new features or priority bug fixes.
<!-- END DONATE -->
**MAINTENANCE OF THIS PLUGIN:** Please note this plugin is maintained **only by me - one person** - in my spare time: I do not get paid for it. Therefore I will do my best to address bugs and issues as time permits but if you have an urgent requirement for a bug fix or missing feature, then I am available for paid contract work in order to expedite this - contact me for details. Otherwise I will get around to it when I have time.
<!-- START doctoc generated TOC please keep comment here to allow auto update -->
<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->
- [Installation](#installation)
- [Plugin variables](#plugin-variables)
- [Android & iOS](#android--ios)
- [Android only](#android-only)
- [iOS only](#ios-only)
- [Post-install plugin variables](#post-install-plugin-variables)
- [Supported Cordova Versions](#supported-cordova-versions)
- [Supported Mobile Platform Versions](#supported-mobile-platform-versions)
- [Migrating from cordova-plugin-firebase](#migrating-from-cordova-plugin-firebase)
- [Breaking API changes](#breaking-api-changes)
- [Ionic 4+](#ionic-4)
- [Ionic 3](#ionic-3)
- [Build environment notes](#build-environment-notes)
- [Remote Cloud Build](#remote-cloud-build)
- [Capacitor support](#capacitor-support)
- [Android-specific](#android-specific)
- [Specifying Android library versions](#specifying-android-library-versions)
- [AndroidX](#androidx)
- [Google Play Services and Firebase libraries](#google-play-services-and-firebase-libraries)
- [iOS-specific](#ios-specific)
- [Specifying iOS library versions](#specifying-ios-library-versions)
- [Cocoapods](#cocoapods)
- [Out-of-date pods](#out-of-date-pods)
- [Strip debug symbols](#strip-debug-symbols)
- [Cordova CLI builds](#cordova-cli-builds)
- [Firebase config setup](#firebase-config-setup)
- [Disable data collection on startup](#disable-data-collection-on-startup)
- [Example project](#example-project)
- [Reporting issues](#reporting-issues)
- [Reporting a bug or problem](#reporting-a-bug-or-problem)
- [Requesting a new feature](#requesting-a-new-feature)
- [Cloud messaging](#cloud-messaging)
- [Background notifications](#background-notifications)
- [Foreground notifications](#foreground-notifications)
- [Android notifications](#android-notifications)
- [Android background notifications](#android-background-notifications)
- [Android foreground notifications](#android-foreground-notifications)
- [Android Notification Channels](#android-notification-channels)
- [Android Notification Icons](#android-notification-icons)
- [Android Notification Color](#android-notification-color)
- [Android Notification Sound](#android-notification-sound)
- [Android cloud message types](#android-cloud-message-types)
- [iOS notifications](#ios-notifications)
- [iOS background notifications](#ios-background-notifications)
- [iOS notification sound](#ios-notification-sound)
- [iOS critical notifications](#ios-critical-notifications)
- [iOS badge number](#ios-badge-number)
- [iOS actionable notifications](#ios-actionable-notifications)
- [iOS notification settings button](#ios-notification-settings-button)
- [Data messages](#data-messages)
- [Data message notifications](#data-message-notifications)
- [Custom FCM message handling](#custom-fcm-message-handling)
- [Android](#android)
- [iOS](#ios)
- [Example](#example)
- [InApp Messaging](#inapp-messaging)
- [Google Tag Manager](#google-tag-manager)
- [Android](#android-1)
- [iOS](#ios-1)
- [Performance Monitoring](#performance-monitoring)
- [Android Performance Monitoring Gradle plugin](#android-performance-monitoring-gradle-plugin)
- [API](#api)
- [Notifications and data messages](#notifications-and-data-messages)
- [getToken](#gettoken)
- [getId](#getid)
- [onTokenRefresh](#ontokenrefresh)
- [getAPNSToken](#getapnstoken)
- [onApnsTokenReceived](#onapnstokenreceived)
- [onOpenSettings](#onopensettings)
- [onMessageReceived](#onmessagereceived)
- [grantPermission](#grantpermission)
- [grantCriticalPermission](#grantcriticalpermission)
- [hasPermission](#haspermission)
- [hasCriticalPermission](#hascriticalpermission)
- [unregister](#unregister)
- [isAutoInitEnabled](#isautoinitenabled)
- [setAutoInitEnabled](#setautoinitenabled)
- [setBadgeNumber](#setbadgenumber)
- [getBadgeNumber](#getbadgenumber)
- [clearAllNotifications](#clearallnotifications)
- [subscribe](#subscribe)
- [unsubscribe](#unsubscribe)
- [createChannel](#createchannel)
- [setDefaultChannel](#setdefaultchannel)
- [Default Android Channel Properties](#default-android-channel-properties)
- [deleteChannel](#deletechannel)
- [listChannels](#listchannels)
- [Analytics](#analytics)
- [setAnalyticsCollectionEnabled](#setanalyticscollectionenabled)
- [isAnalyticsCollectionEnabled](#isanalyticscollectionenabled)
- [AnalyticsConsentMode](#analyticsconsentmode)
- [AnalyticsConsentStatus](#analyticsconsentstatus)
- [setAnalyticsConsentMode](#setanalyticsconsentmode)
- [logEvent](#logevent)
- [setScreenName](#setscreenname)
- [setUserId](#setuserid)
- [setUserProperty](#setuserproperty)
- [initiateOnDeviceConversionMeasurement](#initiateondeviceconversionmeasurement)
- [Crashlytics](#crashlytics)
- [setCrashlyticsCollectionEnabled](#setcrashlyticscollectionenabled)
- [didCrashOnPreviousExecution](#didcrashonpreviousexecution)
- [isCrashlyticsCollectionEnabled](#iscrashlyticscollectionenabled)
- [setCrashlyticsUserId](#setcrashlyticsuserid)
- [sendCrash](#sendcrash)
- [setCrashlyticsCustomKey](#setcrashlyticscustomkey)
- [logMessage](#logmessage)
- [logError](#logerror)
- [Authentication](#authentication)
- [isUserSignedIn](#isusersignedin)
- [signOutUser](#signoutuser)
- [getCurrentUser](#getcurrentuser)
- [reloadCurrentUser](#reloadcurrentuser)
- [updateUserProfile](#updateuserprofile)
- [updateUserEmail](#updateuseremail)
- [sendUserEmailVerification](#senduseremailverification)
- [verifyBeforeUpdateEmail](#verifybeforeupdateemail)
- [updateUserPassword](#updateuserpassword)
- [sendUserPasswordResetEmail](#senduserpasswordresetemail)
- [deleteUser](#deleteuser)
- [createUserWithEmailAndPassword](#createuserwithemailandpassword)
- [signInUserWithEmailAndPassword](#signinuserwithemailandpassword)
- [signInUserWithCustomToken](#signinuserwithcustomtoken)
- [signInUserAnonymously](#signinuseranonymously)
- [verifyPhoneNumber](#verifyphonenumber)
- [enrollSecondAuthFactor](#enrollsecondauthfactor)
- [verifySecondAuthFactor](#verifysecondauthfactor)
- [listEnrolledSecondAuthFactors](#listenrolledsecondauthfactors)
- [unenrollSecondAuthFactor](#unenrollsecondauthfactor)
- [setLanguageCode](#setlanguagecode)
- [authenticateUserWithEmailAndPassword](#authenticateuserwithemailandpassword)
- [authenticateUserWithGoogle](#authenticateuserwithgoogle)
- [authenticateUserWithApple](#authenticateuserwithapple)
- [authenticateUserWithMicrosoft](#authenticateuserwithmicrosoft)
- [authenticateUserWithFacebook](#authenticateuserwithfacebook)
- [authenticateUserWithOAuth](#authenticateuserwithoauth)
- [signInWithCredential](#signinwithcredential)
- [linkUserWithCredential](#linkuserwithcredential)
- [reauthenticateWithCredential](#reauthenticatewithcredential)
- [unlinkUserWithProvider](#unlinkuserwithprovider)
- [registerAuthStateChangeListener](#registerauthstatechangelistener)
- [registerAuthIdTokenChangeListener](#registerauthidtokenchangelistener)
- [useAuthEmulator](#useauthemulator)
- [getClaims](#getclaims)
- [Remote Config](#remote-config)
- [fetch](#fetch)
- [activateFetched](#activatefetched)
- [fetchAndActivate](#fetchandactivate)
- [resetRemoteConfig](#resetremoteconfig)
- [getValue](#getvalue)
- [getInfo](#getinfo)
- [getAll](#getall)
- [setConfigSettings](#setconfigsettings)
- [setDefaults](#setdefaults)
- [Performance](#performance)
- [setPerformanceCollectionEnabled](#setperformancecollectionenabled)
- [isPerformanceCollectionEnabled](#isperformancecollectionenabled)
- [startTrace](#starttrace)
- [incrementCounter](#incrementcounter)
- [stopTrace](#stoptrace)
- [Firestore](#firestore)
- [addDocumentToFirestoreCollection](#adddocumenttofirestorecollection)
- [setDocumentInFirestoreCollection](#setdocumentinfirestorecollection)
- [updateDocumentInFirestoreCollection](#updatedocumentinfirestorecollection)
- [deleteDocumentFromFirestoreCollection](#deletedocumentfromfirestorecollection)
- [documentExistsInFirestoreCollection](#documentexistsinfirestorecollection)
- [fetchDocumentInFirestoreCollection](#fetchdocumentinfirestorecollection)
- [fetchFirestoreCollection](#fetchfirestorecollection)
- [listenToDocumentInFirestoreCollection](#listentodocumentinfirestorecollection)
- [listenToFirestoreCollection](#listentofirestorecollection)
- [removeFirestoreListener](#removefirestorelistener)
- [Functions](#functions)
- [functionsHttpsCallable](#functionshttpscallable)
- [Installations](#installations)
- [getInstallationId](#getinstallationid)
- [getInstallationToken](#getinstallationtoken)
- [getInstallationId](#getinstallationid-1)
- [registerInstallationIdChangeListener](#registerinstallationidchangelistener)
- [Miscellaneous](#miscellaneous)
- [registerApplicationDidBecomeActiveListener](#registerapplicationdidbecomeactivelistener)
- [registerApplicationDidEnterBackgroundListener](#registerapplicationdidenterbackgroundlistener)
- [Debug mode](#debug-mode)
- [Credits](#credits)
<!-- END doctoc generated TOC please keep comment here to allow auto update -->
# Installation
Install the plugin by adding it to your project's config.xml:
```xml
<plugin name="cordova-plugin-firebasex" spec="latest" />
```
or by running:
```
cordova plugin add cordova-plugin-firebasex
```
## Plugin variables
The following Cordova plugin variables are supported by the plugin.
Note that these must be set at plugin installation time. If you wish to change plugin variables, you'll need to uninstall the plugin and reinstall it with the new variable values.
Plugin variables are initially set by specifying them during plugin installation, for example:
`cordova plugin add cordova-plugin-firebasex --variable FIREBASE_ANALYTICS_WITHOUT_ADS=true`
Once the plugin is installed, you can change the plugin variable values either by fully uninstalling/reinstalling the plugin, for example:
`cordova plugin rm cordova-plugin-firebasex && cordova plugin add cordova-plugin-firebasex --variable FIREBASE_ANALYTICS_WITHOUT_ADS=false`
Or you can manually edit the values in your project's `package.json` under `cordova.plugins.cordova-plugin-firebasex` and reinstall the plugin:
`cordova plugin rm cordova-plugin-firebasex --nosave && cordova plugin add cordova-plugin-firebasex --nosave`
### Android & iOS
- `FIREBASE_ANALYTICS_COLLECTION_ENABLED` - whether to automatically enable Firebase Analytics data collection on app startup. Defaults to true.
- `FIREBASE_PERFORMANCE_COLLECTION_ENABLED` - whether to automatically enable Firebase Performance data collection on app startup. Defaults to true.
- `FIREBASE_CRASHLYTICS_COLLECTION_ENABLED` - whether to automatically enable Firebase Crashlytics data collection on app startup. Defaults to true.
- `FIREBASE_FCM_AUTOINIT_ENABLED` - whether to automatically enable FCM registration on app startup. Defaults to true.
- `FIREBASE_ANALYTICS_WITHOUT_ADS` - whether to disable advertising ID collection in Analytics. Defaults to false.
- Note that this is a [post-install plugin variable](#post-install-plugin-variables) so an additional step is required to activate the plugin variable the first time it is specified.
See [Disable data collection on startup](#disable-data-collection-on-startup) for more info.
- `FIREBASE_MESSAGING_IMMEDIATE_PAYLOAD_DELIVERY` - whether to deliver FCM messages immediately when the app is in the background. Defaults to false.
- If false, messages that arrive while the app is in the background/inactive are queued and delivered when the app is next brought to the foreground.
- If true, messages are delivered immediately when received, even if the app is in the background/inactive.
- Note: on modern iOS and Android devices, there is no guarantee that the message will be successfully delivered to the app because the OS may have paused the app's Cordova Webview process or the Webview may not exist at the time the message is received.
- `GOOGLE_ANALYTICS_ADID_COLLECTION_ENABLED` - determines whether Google Analytics collects Advertising IDs (ADIDs) for ad targeting and attribution purposes. If set to true, Google Analytics will collect ADIDs; if set to false, it will not collect ADIDs. Defaults to true.
- `GOOGLE_ANALYTICS_DEFAULT_ALLOW_ANALYTICS_STORAGE` - specifies the default setting for allowing Google Analytics to store analytics data. If set to true, Google Analytics is allowed to store analytics data; if set to false, it is not allowed to store analytics data by default.
- `GOOGLE_ANALYTICS_DEFAULT_ALLOW_AD_STORAGE` - specifies the default setting for allowing Google Analytics to store ad-related data. If set to true, Google Analytics is allowed to store ad-related data; if set to false, it is not allowed to store ad-related data by default. Defaults to true.
- `GOOGLE_ANALYTICS_DEFAULT_ALLOW_AD_USER_DATA` - specifies the default setting for allowing Google Analytics to collect user-related data for ad targeting and personalization. If set to true, Google Analytics is allowed to collect user-related data for ad targeting and personalization; if set to false, it is not allowed to collect such data by default. Defaults to true.
- `GOOGLE_ANALYTICS_DEFAULT_ALLOW_AD_PERSONALIZATION_SIGNALS` - specifies the default setting for allowing Google Analytics to collect signals related to ad personalization. If set to true, Google Analytics is allowed to collect ad personalization signals; if set to false, it is not allowed to collect such signals by default. Defaults to true.
### Android only
The following plugin variables are used to specify the Firebase SDK versions as Gradle dependencies on Android:
- `ANDROID_PLAY_SERVICES_TAGMANAGER_VERSION`
- `ANDROID_PLAY_SERVICES_AUTH_VERSION`
- `ANDROID_FIREBASE_ANALYTICS_VERSION`
- `ANDROID_FIREBASE_MESSAGING_VERSION`
- `ANDROID_FIREBASE_CONFIG_VERSION`
- `ANDROID_FIREBASE_PERF_VERSION`
- `ANDROID_FIREBASE_AUTH_VERSION`
- `$ANDROID_FIREBASE_INAPPMESSAGING_VERSION`
- `ANDROID_FIREBASE_FIRESTORE_VERSION`
- `ANDROID_FIREBASE_FUNCTIONS_VERSION`
- `ANDROID_FIREBASE_INSTALLATIONS_VERSION`
- `ANDROID_FIREBASE_CRASHLYTICS_VERSION`
- `ANDROID_FIREBASE_CRASHLYTICS_NDK_VERSION`
- `ANDROID_GSON_VERSION`
- `ANDROID_FIREBASE_PERF_GRADLE_PLUGIN_VERSION`
- `ANDROID_FIREBASE_PERFORMANCE_MONITORING`
See [Specifying Android library versions](#specifying-android-library-versions) for more info.
- `ANDROID_ICON_ACCENT` - sets the default accent color for system notifications. See [Android Notification Color](#android-notification-color) for more info.
- `ANDROID_FIREBASE_CONFIG_FILEPATH` - sets a custom filepath to `google-services.json` file as a path relative to the project root
- e.g. `--variable ANDROID_FIREBASE_CONFIG_FILEPATH="resources/android/google-services.json"`
- `ANDROID_FIREBASE_PERFORMANCE_MONITORING` - sets whether to add the [Firebase Performance Monitoring Gradle plugin for Android](https://firebase.google.com/docs/perf-mon/get-started-android?authuser=0#add-perfmon-plugin) to the build.
- e.g. `--variable ANDROID_FIREBASE_PERFORMANCE_MONITORING=true`
- Defaults to `false` if not specified.
- `ANDROID_FIREBASE_PERF_GRADLE_PLUGIN_VERSION` - overrides the default version of the [Firebase Performance Monitoring Gradle plugin for Android](https://firebase.google.com/docs/perf-mon/get-started-android?authuser=0#add-perfmon-plugin)
- `ANDROID_GRPC_OKHTTP` - sets version of GRPC OKHTTP library.
### iOS only
- `IOS_FIREBASE_SDK_VERSION` - a specific version of the Firebase iOS SDK to set in the Podfile
- If not specified, the default version defined in `<pod>` elements in the `plugin.xml` will be used.
- `IOS_FIREBASE_IN_APP_MESSAGING_VERSION` - a specific version of the Firebase iOS InAppMessaging SDK to set in the Podfile
- If not specified, the default version defined in `<pod>` elements in the `plugin.xml` will be used.
- `IOS_GOOGLE_SIGIN_VERSION` - a specific version of the Google Sign In library to set in the Podfile
- If not specified, the default version defined in the `<pod>` element in the `plugin.xml` will be used.
- `IOS_GOOGLE_TAG_MANAGER_VERSION` - a specific version of the Google Tag Manager library to set in the Podfile
- If not specified, the default version defined in the `<pod>` element in the `plugin.xml` will be used.
- `IOS_USE_PRECOMPILED_FIRESTORE_POD` - if `true`, switches Podfile to use a [pre-compiled version of the Firestore pod](https://github.com/invertase/firestore-ios-sdk-frameworks.git) to reduce build time
- Defaults to `false` if not specified.
- If you set this option to `true`, you must ensure the environment variable `SKIP_FIREBASE_FIRESTORE_SWIFT` is set **globally** to a truthy value
- e.g. If using zsh: `echo 'export SKIP_FIREBASE_FIRESTORE_SWIFT=1' >> ~/.zshrc && source ~/.zshrc`
- This ensures the pre-built pod is compatible with the Cordova project environment ([see here](https://github.com/invertase/firestore-ios-sdk-frameworks/issues/62))
- Note that this is a [post-install plugin variable](#post-install-plugin-variables) so an additional step is required to activate the plugin variable the first time it is specified.
- If you're having issues building with Firestore, [see here](https://github.com/dpa99c/cordova-plugin-firebasex/wiki#ios-using-pre-built-firestore-pod) for suggested solutions.
- `IOS_STRIP_DEBUG` - prevents symbolification of all libraries included via Cocoapods. See [Strip debug symbols](#strip-debug-symbols) for more info.
- e.g. `--variable IOS_STRIP_DEBUG=true`
- Defaults to `false` if not specified.
- `SETUP_RECAPTCHA_VERIFICATION` - automatically sets up reCAPTCHA verification for phone authentication on iOS. See [verifyPhoneNumber](#verifyphonenumber) for more info.
- e.g. `--variable SETUP_RECAPTCHA_VERIFICATION=true`
- Defaults to `false` if not specified.
- `IOS_SHOULD_ESTABLISH_DIRECT_CHANNEL` - If `true` Firebase Messaging will automatically establish a socket-based, direct channel to the FCM server.
- e.g. `--variable IOS_SHOULD_ESTABLISH_DIRECT_CHANNEL=true`
- Defaults to `false` if not specified.
- See [`shouldEstablishDirectChannel`](<https://firebase.google.com/docs/reference/ios/firebasemessaging/api/reference/Classes/FIRMessaging#/c:objc(cs)FIRMessaging(py)shouldEstablishDirectChannel>)
- Note: Firebase Messaging iOS SDK version 7.0 will be a breaking change where the SDK will no longer support iOS Direct Channel API.
- `IOS_FIREBASE_CONFIG_FILEPATH` - sets a custom filepath to `GoogleService-Info.plist` file as a path relative to the project root
- e.g. `--variable IOS_FIREBASE_CONFIG_FILEPATH="resources/ios/GoogleService-Info.plist"`
- `IOS_ENABLE_APPLE_SIGNIN` - enables the Sign In with Apple capability in Xcode.
- `--variable IOS_ENABLE_APPLE_SIGNIN=true`
- Ensure the associated app provisioning profile also has this capability enabled.
- `IOS_ENABLE_CRITICAL_ALERTS_ENABLED` - enables the critical alerts capability
- `--variable IOS_ENABLE_CRITICAL_ALERTS_ENABLED=true`
- See [iOS critical notifications](#ios-critical-notifications)
- Ensure the associated app provisioning profile also has this capability enabled.
- `IOS_FCM_ENABLED` - allows to completely disable push notifications functionality of the plugin (not just the automatic initialization that is covered by `FIREBASE_FCM_AUTOINIT_ENABLED` variable).
- Defaults to `true`, if not specified; i.e. FCM is enabled by default.
- This can be handy if you are using this plugin for e.g. Crashlytics and handle push notifications using another plugin. Use `--variable IOS_FCM_ENABLED=false` in this case.
- `IOS_ON_DEVICE_CONVERSION_ANALYTICS` - whether to include the On-Device Conversion component of the Firebase SDK.
- Defaults to `false` if not specified.
- If `true`, the component will be included and [initiateOnDeviceConversionMeasurement](#initiateondeviceconversionmeasurement) can be called at run-time to enable it.
- Note that this is a [post-install plugin variable](#post-install-plugin-variables) so an additional step is required to activate the plugin variable the first time it is specified.
### Post-install plugin variables
- Some of the plugin variables above are used to optionally include additional components of the Firebase SDKs.
- Since Cordova does not support using plugin variables to optionally include plugin dependencies, this plugin implements a [custom npm post-install script](scripts/post_install.js) to enable this behaviour.
- This script is executed automatically after the plugin is installed and will apply the plugin variables defined in your project's `package.json` to the plugin's `plugin.xml` file **before** Cordova parses the `plugin.xml` file.
- However, the **first time** you specify a new plugin variable, the post-install script will be executed **before** Cordova has added the plugin variable to the `package.json` file so the plugin variable will not be applied to the `plugin.xml` file.
- **IMPORTANT**: Therefore if you specify a plugin variable for the first time, you must **reinstall** the plugin for the plugin variable to be applied to the `plugin.xml` file:
- e.g. `cordova plugin rm cordova-plugin-firebasex --nosave && cordova plugin add cordova-plugin-firebasex --nosave`
- Note: you do not have to specify the plugin variable(s) again when reinstalling the plugin as they will be read from the `package.json` file.
## Supported Cordova Versions
- cordova: `>= 10`
- cordova-android: `>= 10`
- cordova-ios: `>= 6`
## Supported Mobile Platform Versions
The supported versions of Android and iOS depend on the version of the Firebase SDK included in the build.
See the Firebase [iOS](https://firebase.google.com/support/release-notes/ios) and [Android](https://firebase.google.com/support/release-notes/android) release notes to determine the minimum support OS versions for the SDK version included in your build.
If you didn't explicity specify a version for the Firebase SDK using plugin variables at plugin installation time, you can find the current default version in the plugin's `plugin.xml`.
## Migrating from cordova-plugin-firebase
This plugin is a fork of [cordova-plugin-firebase](https://github.com/arnesson/cordova-plugin-firebase) which has been reworked to fix issues and add new functionality.
If you already have [cordova-plugin-firebase](https://github.com/arnesson/cordova-plugin-firebase) installed in your Cordova project, you need to completely remove it before installing this plugin otherwise they will conflict and cause build errors in your project. The safest way of doing this is as follows:
rm -Rf platforms/android
cordova plugin rm cordova-plugin-firebase
rm -Rf plugins/ node_modules/
npm install
cordova plugin add cordova-plugin-firebasex
cordova platform add android
### Breaking API changes
**IMPORTANT:** Recent versions of `cordova-plugin-firebasex` have made breaking changes to the plugin API in order to fix bugs or add more functionality.
Therefore you can no longer directly substitute `cordova-plugin-firebasex` in place of `cordova-plugin-firebase` without making code changes.
You should be aware of the following breaking changes compared with `cordova-plugin-firebase`:
- Minimum supported Cordova versions
- `cordova@10` (CLI)
- `cordova-android@10` (Android platform)
- `cordova-ios@6` (iOS platform)
- Migrated to AndroidX from legacy Android Support Library
- Migrated to Cocoapods to satisfy Firebase SDK dependencies on iOS
- `onNotificationOpen()` renamed to `onMessageReceived()`
- `tap` parameter is only set when user taps on a notification (not when a message is received from FCM)
- `tap=foreground|background` instead of `tap=true|false`
- `hasPermission()` receives argument as a boolean (rather than an object with `isEnabled` key)
- e.g. `FirebasePlugin.hasPermission(function(hasPermission){
console.log("Permission is " + (hasPermission ? "granted" : "denied"));
});`
- Adds support for foreground notifications and data notification messages
### Ionic 4+
Ionic Native provides a [FirebaseX Typescript wrapper](https://ionicframework.com/docs/native/firebase-x) for using `cordova-plugin-firebasex` with Ionic v4, v5 and above.
Please see their documentation for usage.
First install the package.
```
ionic cordova plugin add cordova-plugin-firebasex
npm install @ionic-native/firebase-x
```
If you're using Angular, register it in your component/service's `NgModule` (for example, app.module.ts) as a provider.
```typescript
import { FirebaseX } from "@ionic-native/firebase-x/ngx";
@NgModule({
//declarations, imports...
providers: [
FirebaseX,
//other providers...
]
})
```
Then you're good to go.
```typescript
import { FirebaseX } from "@ionic-native/firebase-x/ngx";
//...
constructor(private firebase: FirebaseX)
this.firebase.getToken().then(token => console.log(`The token is ${token}`))
this.firebase.onMessageReceived().subscribe(data => console.log(`FCM message: ${data}`));
```
**NOTE:**
- This plugin provides only the Javascript API as documented below.
- The Typescript wrapper is owned and maintain by Ionic.
- Please [report any issues](https://github.com/ionic-team/ionic-native/issues) against the [Ionic Native repo](https://github.com/ionic-team/ionic-native/), not this one.
- Any issues opened against this repo which relate to the Typescript wrapper **will be closed immediately**.
### Ionic 3
The above PR does not work for Ionic 3 so you (currently) can't use the [Ionic Native Firebase](https://ionicframework.com/docs/native/firebase) Typescript wrapper with Ionic 3.
(i.e. `import { Firebase } from "@ionic-native/firebase"` will not work).
To use `cordova-plugin-firebasex` with Ionic 3, you'll need to call its Javascript API directly from your Typescript app code, for example:
```typescript
(<any>window).FirebasePlugin.getToken((token) => console.log(`token: ${token}`))
(<any>window).FirebasePlugin.onMessageReceived((message) => {
if (message.tap) {
console.log(`Notification was tapped in the ${message.tap}`);
}
});
```
If you want to make the `onMessageReceived()` JS API behave like the Ionic Native wrapper:
```javascript
onNotificationOpen() {
return new Observable(observer => {
(window as any).FirebasePlugin.onMessageReceived((response) => {
observer.next(response);
});
});
}
...
this.onNotificationOpen().subscribe(data => console.log(`FCM message: ${data}`));
```
See the [cordova-plugin-firebasex-ionic3-test](https://github.com/dpa99c/cordova-plugin-firebasex-ionic3-test) example project for a demonstration of how to use the plugin with Ionic 3.
# Build environment notes
## Remote Cloud Build
This plugin **will not work** with remote cloud build services that do not support Cordova hook scripts (e.g. [Ionic Appflow](https://ionic.io/appflow)).
The hook scripts used by this plugin are essential to configure the native platform projects for use with the Firebase SDK and therefore if they are not executed, the plugin will not work correctly: either the build will fail or the app containing the plugin will crash at runtime.
Even if the remote build service supports Cordova hook scripts, it is hard to diagnose the cause of build issue because the environment is not under your direct control.
Therefore a **local build environment** is highly recommended since you have full control and the ability to update/upgrade any components in the OS.
Support for using this plugin can only be offered when building projects in a local environment. (i.e. your own development machine).
However if you are unable to build locally and therefore must use a remote build environment, then [VoltBuilder](https://volt.build/) is recommended for use with this plugin as it supports Cordova hook scripts and its developers have explicitly tested building with this plugin to ensure compatibility.
## Capacitor support
This plugin **does not currently support [Capacitor](https://capacitorjs.com/)**. If you want to use Firebase with Capacitor, you should use [Capacitor Firebase](https://github.com/capawesome-team/capacitor-firebase) or the [Firebase JS SDK](https://firebase.google.com/docs/web/setup) instead.
This plugin is designed to work with Cordova therefore relies on Cordova features such as hook scripts, plugin variables and project structure in order to manipulate the native platform projects for use with the Firebase SDK.
## Android-specific
### Specifying Android library versions
This plugin depends on various components such as the Firebase SDK which are pulled in at build-time by Gradle on Android.
By default this plugin pins specific versions of these in [its `plugin.xml`](https://github.com/dpa99c/cordova-plugin-firebase/blob/master/plugin.xml) where you can find the currently pinned versions as `<preference>`'s, for example:
```xml
<preference name="ANDROID_FIREBASE_ANALYTICS_VERSION" default="17.0.0" />
```
The Android defaults can be overridden at plugin installation time by specifying plugin variables as command-line arguments, for example:
cordova plugin add cordova-plugin-firebasex --variable ANDROID_FIREBASE_ANALYTICS_VERSION=17.0.0
Or you can specify them as plugin variables in your `config.xml`, for example:
```xml
<plugin name="cordova-plugin-firebasex" spec="latest">
<variable name="ANDROID_FIREBASE_ANALYTICS_VERSION" value="17.0.0" />
</plugin>
```
The following plugin variables are used to specify the following Gradle dependency versions on Android:
- `ANDROID_PLAY_SERVICES_TAGMANAGER_VERSION` => `com.google.android.gms:play-services-tagmanager`
- `ANDROID_PLAY_SERVICES_AUTH_VERSION` => `com.google.android.gms:play-services-auth`
- `ANDROID_FIREBASE_ANALYTICS_VERSION` => `com.google.firebase:firebase-analytics`
- `ANDROID_FIREBASE_MESSAGING_VERSION` => `com.google.firebase:firebase-messaging`
- `ANDROID_FIREBASE_CONFIG_VERSION` => `com.google.firebase:firebase-config`
- `ANDROID_FIREBASE_PERF_VERSION` => `com.google.firebase:firebase-perf`
- `ANDROID_FIREBASE_AUTH_VERSION` => `com.google.firebase:firebase-auth`
- `ANDROID_FIREBASE_FIRESTORE_VERSION` => `com.google.firebase:firebase-firestore`
- `$ANDROID_FIREBASE_FUNCTIONS_VERSION` => `com.google.firebase:firebase-functions`
- `$ANDROID_FIREBASE_INSTALLATIONS_VERSION` => `com.google.firebase:firebase-installations`
- `$ANDROID_FIREBASE_INAPPMESSAGING_VERSION` => `com.google.firebase:firebase-inappmessaging-display`
- `ANDROID_FIREBASE_CRASHLYTICS_VERSION` => `com.google.firebase:firebase-crashlytics`
- `ANDROID_FIREBASE_CRASHLYTICS_NDK_VERSION` => `com.google.firebase:firebase-crashlytics-ndk`
- `ANDROID_GSON_VERSION` => `com.google.code.gson:gson`
For example:
cordova plugin add cordova-plugin-firebasex \
--variable ANDROID_PLAY_SERVICES_TAGMANAGER_VERSION=17.0.0 \
--variable ANDROID_PLAY_SERVICES_AUTH_VERSION=17.0.0 \
--variable ANDROID_FIREBASE_ANALYTICS_VERSION=17.0.0 \
--variable ANDROID_FIREBASE_MESSAGING_VERSION=19.0.0 \
--variable ANDROID_FIREBASE_CONFIG_VERSION=18.0.0 \
--variable ANDROID_FIREBASE_PERF_VERSION=18.0.0 \
--variable ANDROID_FIREBASE_AUTH_VERSION=18.0.0 \
--variable ANDROID_FIREBASE_CRASHLYTICS_VERSION=17.0.1 \
--variable ANDROID_FIREBASE_CRASHLYTICS_NDK_VERSION=17.0.1 \
### AndroidX
This plugin has been migrated to use [AndroidX (Jetpack)](https://developer.android.com/jetpack/androidx/migrate) which is the successor to the [Android Support Library](https://developer.android.com/topic/libraries/support-library/index).
This is because the [major release of the Firebase and Play Services libraries on 17 June 2019](https://developers.google.com/android/guides/releases#june_17_2019) were migrated to AndroidX.
The `cordova-android@9` platform adds implicit support for AndroidX so (if you haven't already done so) you should update to this platform version:
cordova platform rm android && cordova platform add android@latest
and enable AndroidX by setting the following preference in your `config.xml`:
<preference name="AndroidXEnabled" value="true" />
If you are unable to update from `cordova-android@8`, you can add [cordova-plugin-androidx](https://github.com/dpa99c/cordova-plugin-androidx) to your project which enables AndroidX in the Android platform project:
cordova plugin add cordova-plugin-androidx
If your project includes any plugins which are dependent on the legacy Android Support Library (to which AndroidX is the successor), you should add [cordova-plugin-androidx-adapter](https://github.com/dpa99c/cordova-plugin-androidx-adapter) to your project which will dynamically migrate any plugin code from the Android Support Library to AndroidX equivalents:
cordova plugin add cordova-plugin-androidx-adapter
## Google Play Services and Firebase libraries
Your Android build may fail if you are installing multiple plugins that use the Google Play Services library.
This is caused by plugins installing different versions of the Google Play Services library.
This can be resolved by installing [cordova-android-play-services-gradle-release](https://github.com/dpa99c/cordova-android-play-services-gradle-release) which enables you to override the versions specified by other plugins in order to align them.
Similarly, if your build is failing because multiple plugins are installing different versions of the Firebase library,
you can try installing [cordova-android-firebase-gradle-release](https://github.com/dpa99c/cordova-android-firebase-gradle-release) to align these.
## iOS-specific
Please ensure you have the latest Xcode release version installed to build your app - direct download links can be [found here](https://stackoverflow.com/a/10335943/777265).
### Specifying iOS library versions
This plugin depends on various components such as the Firebase SDK which are pulled in at build-time by Cocoapods on iOS.
This plugin pins specific versions of these in [its `plugin.xml`](https://github.com/dpa99c/cordova-plugin-firebase/blob/master/plugin.xml) where you can find the currently pinned iOS versions in the `<pod>`'s, for example:
<pod name="Firebase/Core" spec="6.3.0"/>
Cordova does not natively support the use of plugin variables in the `<pod>`'s `spec` attribute, however this plugin uses a hook script to enable this behaviour by overriding the version specified in `plugin.xml` directly within the `Podfile`.
Therefore to override the version of the Firebase iOS SDK components set in the `plugin.xml`, you should define it using the `IOS_FIREBASE_SDK_VERSION` plugin variable when installing the plugin into your project.
For example:
cordova plugin add cordova-plugin-firebasex --variable IOS_FIREBASE_SDK_VERSION=9.1.0
### Cocoapods
This plugin relies on Cordova support for the [CocoaPods dependency manager](https://cocoapods.org/) in order to satisfy the iOS Firebase SDK library dependencies.
Please make sure you have `cocoapods@>=1.11.2` installed in your iOS build environment - setup instructions can be found [here](https://cocoapods.org/).
If building your project in Xcode, you need to open `YourProject.xcworkspace` (not `YourProject.xcodeproj`) so both your Cordova app project and the Pods project will be loaded into Xcode.
You can list the pod dependencies in your Cordova iOS project by installing [cocoapods-dependencies](https://github.com/segiddins/cocoapods-dependencies):
sudo gem install cocoapods-dependencies
cd platforms/ios/
pod dependencies
### Out-of-date pods
If you receive a build error such as this:
None of your spec sources contain a spec satisfying the dependencies: `Firebase/Analytics (~> 6.1.0), Firebase/Analytics (= 6.1.0, ~> 6.1.0)`.
Make sure your local Cocoapods repo is up-to-date by running `pod repo update` then run `pod install` in `/your_project/platforms/ios/`.
### Set up project to automatically upload dSYM files
Firebase Documentation [Get started with Firebase Crashlytics](https://firebase.google.com/docs/crashlytics/get-started?platform=ios#set-up-dsym-uploading)
Make sure `cordova-plugin-firebasex` is last plugin in cordova section of your package.json
```json
{
...
"cordova": {
"platforms": [
"browser",
"ios",
"android"
],
"plugins": {
...
"cordova-plugin-firebasex": {
...
}
}
},
....
}
```
### Strip debug symbols
If your iOS app build contains too many debug symbols (i.e. because you include lots of libraries via a Cocoapods), you might get an error (e.g. [issue #28](https://github.com/dpa99c/cordova-plugin-firebase/issues/28)) when you upload your binary to App Store Connect, e.g.:
ITMS-90381: Too many symbol files - These symbols have no corresponding slice in any binary [16EBC8AC-DAA9-39CF-89EA-6A58EB5A5A2F.symbols, 1B105D69-2039-36A4-A04D-96C1C5BAF235.symbols, 476EACDF-583B-3B29-95B9-253CB41097C8.symbols, 9789B03B-6774-3BC9-A8F0-B9D44B08DCCB.symbols, 983BAE60-D245-3291-9F9C-D25E610846AC.symbols].
To prevent this, you can set the `IOS_STRIP_DEBUG` plugin variable which prevents symbolification of all libraries included via Cocoapods ([see here for more information](https://stackoverflow.com/a/48518656/777265)):
cordova plugin add cordova-plugin-firebasex --variable IOS_STRIP_DEBUG=true
By default, this preference is set to `false`.
Note: if you enable this setting, any crashes that occur within libraries included via Cocopods will not be recorded in Crashlytics or other crash reporting services.
### Cordova CLI builds
- Older versions of the Firebase Inapp Messaging SDK and Google Tag Manager SDK components caused [build issues]((https://github.com/apache/cordova-ios/issues/659)) when building via the Cordova CLI.
- Therefore, the `cli_build` branch was kept in sync with `master` but without the above components.
- However, in recent versions, the Firebase Inapp Messaging SDK and Google Tag Manager SDK components no longer cause build issues when building via the Cordova CLI.
- Therefore, the `cli_build` branch is no longer maintained and the `master` branch should be used for Cordova CLI builds.
# Firebase config setup
There's a handy [installation and setup guide on medium.com](https://medium.com/@felipepucinelli/how-to-add-push-notifications-in-your-cordova-application-using-firebase-69fac067e821).
However, if using this, remember this forked plugin is `cordova-plugin-firebasex` (not `cordova-plugin-firebase`).
Download your Firebase configuration files, `GoogleService-Info.plist` for iOS and `google-services.json` for android, and place them in the root folder of your cordova project.
Check out this [firebase article](https://support.google.com/firebase/answer/7015592) for details on how to download the files.
```
- My Project/
platforms/
plugins/
www/
config.xml
google-services.json <--
GoogleService-Info.plist <--
...
```
Or you can set custom location for your platform configuration files using plugin variables in your `config.xml`:
```
<plugin name="cordova-plugin-firebasex">
<variable name="ANDROID_FIREBASE_CONFIG_FILEPATH" value="resources/android/google-services.json" />
<variable name="IOS_FIREBASE_CONFIG_FILEPATH" value="resources/ios/GoogleService-Info.plist" />
</plugin>
```
IMPORTANT: The Firebase SDK requires the configuration files to be present and valid, otherwise your app will crash on boot or Firebase features won't work.
# Disable data collection on startup
By default, analytics, performance and Crashlytics data will begin being collected as soon as the app starts up.
However, for data protection or privacy reasons, you may wish to disable data collection until such time as the user has granted their permission.
To do this, set the following plugin variables to `false` at plugin install time:
- `FIREBASE_ANALYTICS_COLLECTION_ENABLED`
- `FIREBASE_PERFORMANCE_COLLECTION_ENABLED`
- `FIREBASE_CRASHLYTICS_COLLECTION_ENABLED`
- `GOOGLE_ANALYTICS_ADID_COLLECTION_ENABLED`
- `GOOGLE_ANALYTICS_DEFAULT_ALLOW_ANALYTICS_STORAGE`
- `GOOGLE_ANALYTICS_DEFAULT_ALLOW_AD_STORAGE`
- `GOOGLE_ANALYTICS_DEFAULT_ALLOW_AD_USER_DATA`
- `GOOGLE_ANALYTICS_DEFAULT_ALLOW_AD_PERSONALIZATION_SIGNALS`
cordova plugin add cordova-plugin-firebasex \
--variable FIREBASE_ANALYTICS_COLLECTION_ENABLED=false \
--variable FIREBASE_PERFORMANCE_COLLECTION_ENABLED=false \
--variable FIREBASE_CRASHLYTICS_COLLECTION_ENABLED=false \
--variable GOOGLE_ANALYTICS_ADID_COLLECTION_ENABLED=false \
--variable GOOGLE_ANALYTICS_DEFAULT_ALLOW_ANALYTICS_STORAGE=false \
--variable GOOGLE_ANALYTICS_DEFAULT_ALLOW_AD_STORAGE=false \
--variable GOOGLE_ANALYTICS_DEFAULT_ALLOW_AD_USER_DATA=false \
--variable GOOGLE_ANALYTICS_DEFAULT_ALLOW_AD_PERSONALIZATION_SIGNALS=false
This will disable data collection (on both Android & iOS) until you call [setAnalyticsCollectionEnabled](#setanalyticscollectionenabled), [setPerformanceCollectionEnabled](#setperformancecollectionenabled), [setCrashlyticsCollectionEnabled](#setcrashlyticscollectionenabled) and [setAnalyticsConsentMode](#setanalyticsconsentmode):
FirebasePlugin.setAnalyticsCollectionEnabled(true);
FirebasePlugin.setPerformanceCollectionEnabled(true);
FirebasePlugin.setCrashlyticsCollectionEnabled(true);
FirebasePlugin.setAnalyticsConsentMode({
ANALYTICS_STORAGE: "GRANTED",
AD_STORAGE: "GRANTED",
AD_USER_DATA: "GRANTED",
AD_PERSONALIZATION: "GRANTED",
});
Notes:
- Calling `setXCollectionEnabled()` will have no effect if the corresponding `FIREBASE_X_COLLECTION_ENABLED` variable is set to `true`.
- Calling `setXCollectionEnabled(true|false)` will enable/disable data collection during the current app session and across subsequent app sessions until such time as the same method is called again with a different value.
# Example project
An example project repo exists to demonstrate and validate the functionality of this plugin:
https://github.com/dpa99c/cordova-plugin-firebasex-test
Please use this as a working reference.
Before reporting any issues, please (if possible) test against the example project to rule out causes external to this plugin.
# Reporting issues
**IMPORTANT:** Please read the following carefully.
Failure to follow the issue template guidelines below will result in the issue being immediately closed.
## Reporting a bug or problem
Before [opening a bug issue](https://github.com/dpa99c/cordova-plugin-firebasex/issues/new?assignees=&labels=&template=bug_report.md&title=), please do the following:
- _DO NOT_ open issues asking for support in using/integrating the plugin into your project
- Only open issues for suspected bugs/issues with the plugin that are generic and will affect other users
- I don't have time to offer free technical support: this is free open-source software
- Ask for help on StackOverflow, Ionic Forums, etc.
- Use the [example project](https://github.com/dpa99c/cordova-plugin-firebasex-test) as a known working reference
- Any issues requesting support will be closed immediately.
- _DO NOT_ open issues related to the [Ionic Typescript wrapper for this plugin](https://github.com/ionic-team/ionic-native/blob/master/src/%40awesome-cordova-plugins/plugins/firebase-x/index.ts)
- This is owned/maintained by [Ionic](https://github.com/ionic-team) and is not part of this plugin
- Please raise such issues/PRs against [Ionic Native](https://github.com/ionic-team/ionic-native/) instead.
- To verify an if an issue is caused by this plugin or its Typescript wrapper, please re-test using the vanilla Javascript plugin interface (without the Ionic Native wrapper).
- Any issue opened here which is obviously an Ionic Typescript wrapper issue will be closed immediately.
- _DO NOT_ open issues related to [Remote Cloud Build](#remote-cloud-build) environments such as [Ionic Appflow](https://ionic.io/appflow) as these are not supported
- If you are migrating from [cordova-plugin-firebase](https://github.com/arnesson/cordova-plugin-firebase) to `cordova-plugin-firebasex` please make sure you have read the [Migrating from cordova-plugin-firebase](#migrating-from-cordova-plugin-firebase) section.
- Read the above documentation thoroughly
- For example, if you're having a build issue ensure you've read through the [build environment notes](#build-environment-notes)
- If an iOS CLI build is failing, ensure you've read the [Cordova CLI builds](#cordova-cli-builds) section
- Check the [CHANGELOG](https://github.com/dpa99c/cordova-plugin-firebasex/blob/master/CHANGELOG.md) for any breaking changes that may be causing your issue.
- Check a similar issue (open or closed) does not already exist against this plugin.
- Duplicates or near-duplicates will be closed immediately.
- When [creating a new issue](https://github.com/dpa99c/cordova-plugin-firebasex/issues/new/choose)
- Choose the "Bug report" template
- Fill out the relevant sections of the template and delete irrelevant sections
- _WARNING:_ Failure to complete the issue template will result in the issue being closed immediately.
- **Reproduce the issue using the [example project](https://github.com/dpa99c/cordova-plugin-firebasex-test)**
- This will eliminate bugs in your code or conflicts with other code as possible causes of the issue
- This will also validate your development environment using a known working codebase
- If reproducing the issue using the example project is not possible, create an isolated test project that you are able to share
- **Support cannot be offered to help resolve build issues in your own project.**
- Include full verbose console output when reporting build issues
- If the full console output is too large to insert directly into the Github issue, then post it on an external site such as [Pastebin](https://pastebin.com/) and link to it from the issue
- Often the details of an error causing a build failure is hidden away when building with the CLI
- To get the full detailed console output, append the `--verbose` flag to CLI build commands
- e.g. `cordova build ios --verbose`
- Failure to include the full console output will result in the issue being closed immediately
- If the issue relates to the plugin documentation (and not the code), please of a [documentation issue](https://github.com/dpa99c/cordova-plugin-firebasex/issues/new?assignees=&labels=&template=documentation-issue.md&title=)
## Requesting a new feature
Before [opening a feature request issue](https://github.com/dpa99c/cordova-plugin-firebasex/issues/new?assignees=&labels=&template=feature_request.md&title=), please do the following:
- Check the above documentation to ensure the feature you are requesting doesn't already exist
- Check the list if open/closed issues to check if there's a reason that feature hasn't been included already
- Ensure the feature you are requesting is actually possible to implement and generically useful to other users than yourself
- Where possible, post a link to the documentat