> For the complete documentation index, see [llms.txt](https://en.docs.monaca.io/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://en.docs.monaca.io/tutorials/firebase.md).

# Cordova Firebase Plugin

This Cordova plugin brings push notifications, analytics, event tracking, crash reporting and more from Google Firebase to your Cordova project.

* Repository: <https://github.com/dpa99c/cordova-plugin-firebasex>
* Plugin ID/package name: `cordova-plugin-firebasex`
* Tested version: 16.5.0

{% hint style="info" %}
Cordova Firebase Plugin 16.5.0 supports Privacy Manifests.
{% endhint %}

{% hint style="info" %}
The custom build debugger can not check push notifications. To check push notifications, please check with a debug build or a release build.
{% endhint %}

## Demo

[<img src="https://docs.monaca.io/images/common/import_img.png" alt="" data-size="line">Import Google Firebase plugin demo to your Monaca account](https://monaca.mobi/ja/directimport?pid=64b92d32e78885c623d49611)

![](https://docs.monaca.io/images/samples/firebase.png)

## Preparation for iOS

When working with push notifications for iOS, an APNs authentication key or an APNs certificate is required. On this page, we will show you how to create a development APNs certificate for testing on an iOS debug build.

{% hint style="info" %}
For a release build, a production APNs certificate is required.
{% endhint %}

In order to create a development APNs certificate, you should have signed up for the [Apple Developer Program](https://developer.apple.com/programs/). Follow the instructions below to create the certificate:

1. From the [Apple Developer page](https://developer.apple.com/), go to `Account`.
2. Select **Certificates, Identifiers & Profiles**.

![](/files/-MgEJTTzwmJCkCjMniZk)

3\. An App ID with push notifications enabled is required when creating an APNs certificate. Therefore, let’s create one. Under the `Identifiers` section, go to **App IDs** and click the :heavy\_plus\_sign: button in the upper right corner.

![](https://docs.monaca.io/images/tutorials/14.png)

4\. Fill in the following information:

* `App Description`: Input your app name here (e.g. Cordova Firebase Demo)
* `Explicit ID`: Select this option because a Wildcard App ID is not allowed for push notifications. Input a unique identifier for your app (e.g. `io.monaca.firebase`).

![](https://docs.monaca.io/images/tutorials/15.png)

5\. Scroll down to `App Services` section and tick the **Push Notifications** option. Then, click **Continue**.

![](https://docs.monaca.io/images/tutorials/16.png)

6\. You will be redirected to the `Confirm your App ID` page. Click **Register** to complete the process.

7\. Now, you should be back on the iOS App IDs page. Select the App ID you’ve just created and click **Edit**.

8\. Scroll down to the `Push Notifications` section and click **Create Cerficate** under `Development SSL Certificate`.

![](https://docs.monaca.io/images/tutorials/17.png)

9\. Click **Continue**.

10\. After that, click **Choose File** to browse your CSR file. You can get this file from the Monaca Cloud IDE by going to **Config → iOS Build Settings**. Then, click **Generate Key and CSR**. After creating the CSR file, download it by clicking the **Export** button.

11\. Next, click **Continue** again. When the certificate is ready, you can download it. Keep the file.

12\. Upload the downloaded certificate by clicking the **Upload Certificate** button in the `iOS Build Settings`.

13\. Click the **Export** icon of the target certificate displayed in `Certificates registered in Monaca` to export the p12 file. You will need it for the  Firebase configuration in the upcoming section.

## Configuring Firebase for push notifications

1. Go to [Firebase Console](https://firebase.google.com/).
2. Sign in with your Google account to enter the console.
3. Click **Add project**.

![](/files/-MgEJrnpe5EopP1ieVQP)

4\. Fill in the project information and click **CREATE PROJECT**. You will be redirected to the `Project Overview` page.

![](https://docs.monaca.io/images/tutorials/2.png)

After creating a project, we can start configuring the push notification project for a specific platform.

### For iOS

1. Go to the `Project settings`.

![](/files/-MgEK4qO84vuG-VT1G2d)

2\. Under the `General` section, click **ADD APP** and select `iOS`.

3\. Enter your iOS Bundle ID (You can find it by going to **Config → iOS App Settings**). Then, click **REGISTER APP**.

![](https://docs.monaca.io/images/tutorials/4.png)

4\. Download the `GoogleService-Info.plist` file and place it in the root folder of your project. After that, click **CONTINUE**.

![](https://docs.monaca.io/images/tutorials/5.png)

5\. You will see instructions for adding the Firebase SDK into our project. However, we are not developing the app natively so we can skip this step. Just click **CONTINUE** to proceed. Then, click **FINISH** to complete the configuration. After that, you should see your iOS app on the `Firebase overview` page.

![](https://docs.monaca.io/images/tutorials/6.png)

6\. Now, it’s time to add the APNs certificates into this project. Go to `Project settings` and select **CLOUD MESSAGING**.

![](https://docs.monaca.io/images/tutorials/3.png)

7\. Scroll down to the `iOS app configuration` section and upload the APNs authentication key or the APNs certificates.

![](https://docs.monaca.io/images/tutorials/7.png)

That's it! You are done with the iOS configuration.

### For Android

1. Go to the `Project settings`.

![](/files/-MgEKOai4AQMXq4XygR_)

2\. Under the `General` section, click **ADD APP** and select **Android**.

3\. Enter your package name (You can find that by going to **Config → Android App Settings**). Then, click **REGISTER APP**.

![](https://docs.monaca.io/images/tutorials/8.png)

4\. Download `google-services.json` file and place it in the root folder of your project. After that, click **CONTINUE**.

![](https://docs.monaca.io/images/tutorials/9.png)

5\. You will see instructions for adding the Firebase SDK into our project. However, we are not developing the app natively so we can skip this step. Just click **FINISH** to complete the configuration. After that, you should see your Android app in the `Firebase overview` page.

![](https://docs.monaca.io/images/tutorials/10.png)

## Adding the plugin to the Monaca IDE

1. From the Monaca IDE menu, go to **Config → Manage Cordova Plugins**.
2. Click the **Import Cordova Plugin** button. Then, you can choose to import the plugin using a ZIP file or URL/package name.

{% hint style="info" %}
To support iOS 12.2+ devices, configure your config.xml as follows:

```xml
  <platform name="ios">
    <preference name="deployment-target" value="12.2"/>
```

{% endhint %}

## Usage

After importing the plugin to the project, you can start using it by generating a token for your device and setting an event for when a user opens a notification. Please make sure to call the plugin API after the Cordova is loaded.

```javascript
document.addEventListener("deviceready", function(){
    window.FirebasePlugin.getToken(function(token) {
        // save this server-side and use it to push notifications to this device
        console.log(token);
    }, function(error) {
        console.error(error);
    });

    // Get notified when a token is refreshed
    window.FirebasePlugin.onTokenRefresh(function(token) {
        // save this server-side and use it to push notifications to this device
        console.log("Refresh to get new token: " + token);
    }, function(error) {
        alert(error);
    });

    // Get notified when the user opens a notification
    window.FirebasePlugin.onMessageReceived(function(message) {
        console.log("Message type: " + message.messageType);
        if(message.messageType === "notification"){
            alert("Notification message received");
            if(message.tap){
                alert("Tapped in " + message.tap);
            }
        }
    }, function(error) {
        console.error(error);
    }); 
}, false);
```

## API references

In this section, we only describe some main APIs used in our [Demo](https://monaca.mobi/directimport?pid=5ac5776ee788854f3a8b456a). For a complete list of the API references, please refer to [here](https://github.com/dpa99c/cordova-plugin-firebasex#api).

### getToken()

Get the device token. The token will be null if it is not established yet.

```javascript
window.FirebasePlugin.getToken();
```

**Example**

```javascript
window.FirebasePlugin.getToken(function(token) {
    // save this server-side and use it to push notifications to this device
    console.log(token);
}, function(error) {
    console.error(error);
});
```

### onTokenRefresh()

Get notified when a token is refreshed. This is the best way to get a valid token for a device as soon as the token is established.

```javascript
window.FirebasePlugin.onTokenRefresh();
```

**Example**

```javascript
window.FirebasePlugin.onTokenRefresh(function(token) {
    // save this server-side and use it to push notifications to this device
    console.log(token);
}, function(error) {
    console.error(error);
});
```

### onMessageReceived()

Get notified when a notification is opened.

```javascript
window.FirebasePlugin.onMessageReceived();
```

**Example**

```javascript
window.FirebasePlugin.onMessageReceived(function(message) {
    console.log("Message type: " + message.messageType);
    if(message.messageType === "notification"){
        alert("Notification message received");
        if(message.tap){
            alert("Tapped in " + message.tap);
        }
    }
}, function(error) {
    console.error(error);
});
```

### hasPermission()

Check the permission to receive push notifications.

```javascript
window.FirebasePlugin.hasPermission();
```

**Example**

```javascript
window.FirebasePlugin.hasPermission(function(hasPermission){
    if (hasPermission)
        alert("Permission to receive notification is granted.");
    else
        alert("Permission to receive notification is NOT granted.");
});
```

### grantPermission() (iOS only)

Grant permission to receive push notifications for iOS (will trigger a prompt if the permission has not been granted yet).

```javascript
window.FirebasePlugin.grantPermission();
```

**Example**

```javascript
window.FirebasePlugin.grantPermission(function(){
    alert("Permission is granted for iOS");    
}, function(error){
    alert(error);
});
```

### setBadgeNumber()

Set a number on the icon badge.

```javascript
window.FirebasePlugin.setBadgeNumber(badgeNumber);
```

**Parameter**

| Name          | Type   | Description                  |
| ------------- | ------ | ---------------------------- |
| `badgeNumber` | Number | The number on the icon badge |

**Example**

After setting the badge number, close the app. Then, you will see the badge number appear on your app icon. If you want to remove the number, set it to `0`.

```javascript
window.FirebasePlugin.setBadgeNumber(5);
```

### getBadgeNumber()

Get the icon badge number.

```javascript
window.FirebasePlugin.getBadgeNumber();
```

**Example**

```javascript
window.FirebasePlugin.getBadgeNumber(function(n) {
        alert("Badge Number is " + n);
    });
```

### unregister()

Unregister from Firebase to stop receiving push notifications. Call this when you logout user from your app.

```javascript
window.FirebasePlugin.unregister();
```

**Example**

```javascript
window.FirebasePlugin.unregister(function(){
    alert("Stop receiving push notifications."); 
}, function(error){
    alert(error);
});
```

### setScreenName()

Set the name of the current screen in the analytics.

```javascript
window.FirebasePlugin.setScreenName(screenName);
```

**Parameter**

| Name         | Type   | Description |
| ------------ | ------ | ----------- |
| `screenName` | String | Screen name |

**Example**

```javascript
var page="FirebaseHome";
window.FirebasePlugin.setScreenName(page);
alert(page + " screen is tracked.");
```

### setUserId()

Set a user id for the analytics.

```javascript
window.FirebasePlugin.setUserId(id);
```

**Parameter**

| Name | Type   | Description                                                                         |
| ---- | ------ | ----------------------------------------------------------------------------------- |
| `id` | String | A unique identifier, associated with a particular user. Must be sent with each hit. |

**Example**

```javascript
//user ID for testing purpose
var myUserId="35009a79-1a05-49d7-b876-2b884d0f825b";
window.FirebasePlugin.setUserId("user_id");
alert("UserID is set to: " + myUserId);
```
