Add push notifications to your Apache Cordova app

Overview

In this tutorial, you add push notifications to the [Apache Cordova quick start] project so that a push notification is sent to the device every time a record is inserted.

If you do not use the downloaded quick start server project, you need the push notification extension package. For more information, see Work with the .NET backend server SDK for Azure Mobile Apps.

Prerequisites

This tutorial covers an Apache Cordova application developed with Visual Studio 2015 that runs on the Google Android Emulator, an Android device, a Windows device, and an iOS device.

To complete this tutorial, you need:

Configure a notification hub

The Mobile Apps feature of Azure App Service uses Azure Notification Hubs to send pushes, so you will be configuring a notification hub for your mobile app.

  1. In the Azure portal, go to App Services, and then click your app back end. Under Settings, click Push.
  2. Click Connect to add a notification hub resource to the app. You can either create a hub or connect to an existing one.

Now you have connected a notification hub to your Mobile Apps back-end project. Later you will configure this notification hub to connect to a platform notification system (PNS) to push to devices.

Watch a video showing steps in this section

Update the server project

In this section, you update code in your existing Mobile Apps back-end project to send a push notification every time a new item is added. This is powered by the template feature of Azure Notification Hubs, enabling cross-platform pushes. The various clients are registered for push notifications using templates, and a single universal push can get to all client platforms.

Choose one of the following procedures that matches your back-end project type—either .NET back end or Node.js back end.

.NET back-end project

  1. In Visual Studio, right-click the server project and click Manage NuGet Packages. Search for Microsoft.Azure.NotificationHubs, and then click Install. This installs the Notification Hubs library for sending notifications from your back end.
  2. In the server project, open Controllers > TodoItemController.cs, and add the following using statements:

     using System.Collections.Generic;
     using Microsoft.Azure.NotificationHubs;
     using Microsoft.Azure.Mobile.Server.Config;
    
  3. In the PostTodoItem method, add the following code after the call to InsertAsync:

     // Get the settings for the server project.
     HttpConfiguration config = this.Configuration;
     MobileAppSettingsDictionary settings =
         this.Configuration.GetMobileAppSettingsProvider().GetMobileAppSettings();
    
     // Get the Notification Hubs credentials for the Mobile App.
     string notificationHubName = settings.NotificationHubName;
     string notificationHubConnection = settings
         .Connections[MobileAppSettingsKeys.NotificationHubConnectionString].ConnectionString;
    
     // Create a new Notification Hub client.
     NotificationHubClient hub = NotificationHubClient
     .CreateClientFromConnectionString(notificationHubConnection, notificationHubName);
    
     // Sending the message so that all template registrations that contain "messageParam"
     // will receive the notifications. This includes APNS, GCM, WNS, and MPNS template registrations.
     Dictionary<string,string> templateParams = new Dictionary<string,string>();
     templateParams["messageParam"] = item.Text + " was added to the list.";
    
     try
     {
         // Send the push notification and log the results.
         var result = await hub.SendTemplateNotificationAsync(templateParams);
    
         // Write the success result to the logs.
         config.Services.GetTraceWriter().Info(result.State.ToString());
     }
     catch (System.Exception ex)
     {
         // Write the failure result to the logs.
         config.Services.GetTraceWriter()
             .Error(ex.Message, null, "Push.SendAsync Error");
     }
    

    This sends a template notification that contains the item.Text when a new item is inserted.

  4. Republish the server project.

Node.js back-end project

  1. If you haven't already done so, download the quickstart back-end project, or else use the online editor in the Azure portal.
  2. Replace the existing code in todoitem.js with the following:

     var azureMobileApps = require('azure-mobile-apps'),
     promises = require('azure-mobile-apps/src/utilities/promises'),
     logger = require('azure-mobile-apps/src/logger');
    
     var table = azureMobileApps.table();
    
     table.insert(function (context) {
     // For more information about the Notification Hubs JavaScript SDK,
     // see http://aka.ms/nodejshubs
     logger.info('Running TodoItem.insert');
    
     // Define the template payload.
     var payload = '{"messageParam": "' + context.item.text + '" }';  
    
     // Execute the insert.  The insert returns the results as a Promise,
     // Do the push as a post-execute action within the promise flow.
     return context.execute()
         .then(function (results) {
             // Only do the push if configured
             if (context.push) {
                 // Send a template notification.
                 context.push.send(null, payload, function (error) {
                     if (error) {
                         logger.error('Error while sending push notification: ', error);
                     } else {
                         logger.info('Push notification sent successfully!');
                     }
                 });
             }
             // Don't forget to return the results from the context.execute()
             return results;
         })
         .catch(function (error) {
             logger.error('Error while running context.execute: ', error);
         });
     });
    
     module.exports = table;  
    

    This sends a template notification that contains the item.text when a new item is inserted.

  3. When editing the file on your local computer, republish the server project.

Modify your Cordova app

Ensure your Apache Cordova app project is ready to handle push notifications by installing the Cordova push plugin plus any platform-specific push services.

Update the Cordova version in your project.

If your project uses a version of Apache Cordova earlier than v6.1.1, update the client project. To update the project:

  • Right-click config.xml to open the configuration designer.
  • Select the Platforms tab.
  • Choose 6.1.1 in the Cordova CLI text box.
  • Choose Build, then Build Solution to update the project.

Install the push plugin

Apache Cordova applications do not natively handle device or network capabilities. These capabilities are provided by plugins that are published either on npm or on GitHub. The phonegap-plugin-push plugin is used to handle network push notifications.

You can install the push plugin in one of these ways:

From the command-prompt:

Execute the following command:

cordova plugin add phonegap-plugin-push

From within Visual Studio:

  1. In Solution Explorer, open the config.xml file click Plugins > Custom, select Git as the installation source, then enter https://github.com/phonegap/phonegap-plugin-push as the source.

  2. Click the arrow next to the installation source.

  3. In SENDER_ID, if you already have a numeric project ID for the Google Developer Console project, you can add it here. Otherwise, enter a placeholder value, like 777777. If you are targeting Android, you can update this value in config.xml later.
  4. Click Add.

The push plugin is now installed.

Install the device plugin

Follow the same procedure you used to install the push plugin. Add the Device plugin from the Core plugins list (click Plugins > Core to find it). You need this plugin to obtain the platform name.

Register your device on application start-up

Initially, we include some minimal code for Android. Later, modify the app to run on iOS or Windows 10.

  1. Add a call to registerForPushNotifications during the callback for the login process, or at the bottom of the onDeviceReady method:

     // Login to the service.
     client.login('google')
         .then(function () {
             // Create a table reference
             todoItemTable = client.getTable('todoitem');
    
             // Refresh the todoItems
             refreshDisplay();
    
             // Wire up the UI Event Handler for the Add Item
             $('#add-item').submit(addItemHandler);
             $('#refresh').on('click', refreshDisplay);
    
                 // Added to register for push notifications.
             registerForPushNotifications();
    
         }, handleError);
    

    This example shows calling registerForPushNotifications after authentication succeeds. You can call registerForPushNotifications() as often as is required.

  2. Add the new registerForPushNotifications method as follows:

     // Register for Push Notifications. Requires that phonegap-plugin-push be installed.
     var pushRegistration = null;
     function registerForPushNotifications() {
       pushRegistration = PushNotification.init({
           android: { senderID: 'Your_Project_ID' },
           ios: { alert: 'true', badge: 'true', sound: 'true' },
           wns: {}
       });
    
     // Handle the registration event.
     pushRegistration.on('registration', function (data) {
       // Get the native platform of the device.
       var platform = device.platform;
       // Get the handle returned during registration.
       var handle = data.registrationId;
       // Set the device-specific message template.
       if (platform == 'android' || platform == 'Android') {
           // Register for GCM notifications.
           client.push.register('gcm', handle, {
               mytemplate: { body: { data: { message: "{$(messageParam)}" } } }
           });
       } else if (device.platform === 'iOS') {
           // Register for notifications.
           client.push.register('apns', handle, {
               mytemplate: { body: { aps: { alert: "{$(messageParam)}" } } }
           });
       } else if (device.platform === 'windows') {
           // Register for WNS notifications.
           client.push.register('wns', handle, {
               myTemplate: {
                   body: '<toast><visual><binding template="ToastText01"><text id="1">$(messageParam)</text></binding></visual></toast>',
                   headers: { 'X-WNS-Type': 'wns/toast' } }
           });
       }
     });
    
     pushRegistration.on('notification', function (data, d2) {
       alert('Push Received: ' + data.message);
     });
    
     pushRegistration.on('error', handleError);
     }
    
  3. (Android) In the preceding code, replace Your_Project_ID with the numeric project ID for your app from the Google Developer Console.

(Optional) Configure and run the app on Android

Complete this section to enable push notifications for Android.

Enable Firebase Cloud Messaging

Since we are targeting the Google Android platform initially, you must enable Firebase Cloud Messaging.

  1. Sign in to the Firebase console. Create a new Firebase project if you don't already have one.
  2. After your project is created, click Add Firebase to your Android app and follow the instructions provided.

  3. In the Firebase console, click the cog for your project and then click Project Settings.

  4. Click the Cloud Messaging tab in your project settings, and copy the value of the Server key and Sender ID. These values will be used later to configure the notification hub access policy, and your notification handler in the app.

Configure the Mobile App backend to send push requests using FCM

  1. In the Azure portal, click Browse All > App Services, and click your Mobile Apps back end. Under Settings, click App Service Push, and then click your notification hub name.
  2. Go to Google (GCM), enter the FCM server key you obtained from the Firebase console, and then click Save.

Your service is now configured to work with Firebase Cloud Messaging.

Configure your Cordova app for Android

In your Cordova app, open config.xml and replace Your_Project_ID with the numeric project ID for your app from the Google Developer Console.

    <plugin name="phonegap-plugin-push" version="1.7.1" src="https://github.com/phonegap/phonegap-plugin-push.git">
        <variable name="SENDER_ID" value="Your_Project_ID" />
    </plugin>

Open index.js and update the code to use your numeric project ID.

    pushRegistration = PushNotification.init({
        android: { senderID: 'Your_Project_ID' },
        ios: { alert: 'true', badge: 'true', sound: 'true' },
        wns: {}
    });

Configure your Android device for USB debugging

Before you can deploy your application to your Android Device, you need to enable USB Debugging. Perform the following steps on your Android phone:

  1. Go to Settings > About phone, then tap the Build number until developer mode is enabled (about seven times).
  2. Back in Settings > Developer Options enable USB debugging, then connect your Android phone to your development PC with a USB Cable.

We tested this using a Google Nexus 5X device running Android 6.0 (Marshmallow). However, the techniques are common across any modern Android release.

Install Google Play Services

The push plugin relies on Android Google Play Services for push notifications.

  1. In Visual Studio, click Tools > Android > Android SDK Manager, expand the Extras folder and check the box to make sure that each of the following SDKs is installed.

    • Android 2.3 or higher
    • Google Repository revision 27 or higher
    • Google Play Services 9.0.2 or higher
  2. Click Install Packages and wait for the installation to complete.

The current required libraries are listed in the phonegap-plugin-push installation documentation.

Test push notifications in the app on Android

You can now test push notifications by running the app and inserting items in the TodoItem table. You can test from the same device or from a second device, as long as you are using the same backend. Test your Cordova app on the Android platform in one of the following ways:

  • On a physical device: Attach your Android device to your development computer with a USB cable. Instead of Google Android Emulator, select Device. Visual Studio deploys the application to the device and then runs the application. You can then interact with the application on the device.

    Improve your development experience. Screen sharing applications such as Mobizen can assist you in developing an Android application. Mobizen projects your Android screen to a web browser on your PC.

  • On an Android emulator: There are additional configuration steps required when running on an emulator.

    Make sure you are deploying to a virtual device that has Google APIs set as the target, as shown in the Android Virtual Device (AVD) manager.

    If you want to use a faster x86 emulator, you install the HAXM driver and configure the emulator to use it.

    Add a Google account to the Android device by clicking Apps > Settings > Add account, then follow the prompts.

    Run the todolist app as before and insert a new todo item. This time, a notification icon is displayed in the notification area. You can open the notification drawer to view the full text of the notification.

(Optional) Configure and run on iOS

This section is for running the Cordova project on iOS devices. If you are not working with iOS devices, you can skip this section.

Install and run the iOS remote build agent on a Mac or cloud service

Before you can run a Cordova app on iOS using Visual Studio, go through the steps in the iOS Setup Guide to install and run the remote build agent.

Make sure you can build the app for iOS. The steps in the setup guide are required to build for iOS from Visual Studio. If you do not have a Mac, you can build for iOS using the remote build agent on a service like MacInCloud. For more info, see Run your iOS app in the cloud.

Note

XCode 7 or greater is required to use the push plugin on iOS.

Find the ID to use as your App ID

Before you register your app for push notifications, open config.xml in your Cordova app, find the id attribute value in the widget element, and copy it for later use. In the following XML, the ID is io.cordova.myapp7777777.

    <widget defaultlocale="en-US" id="io.cordova.myapp7777777"
      version="1.0.0" windows-packageVersion="1.1.0.0" xmlns="http://www.w3.org/ns/widgets"
        xmlns:cdv="http://cordova.apache.org/ns/1.0" xmlns:vs="http://schemas.microsoft.com/appx/2014/htmlapps">

Later, use this identifier when you create an App ID on Apple's developer portal. If you create a different App ID on the developer portal, you must take a few extra steps later in this tutorial. The ID in the widget element must match the App ID on the developer portal.

Register the app for push notifications on Apple's developer portal

Watch a video showing similar steps

Configure Azure to send push notifications

  1. On your Mac, launch Keychain Access. On the left navigation bar, under Category, open My Certificates. Find the SSL certificate you downloaded in the previous section, and disclose its contents. Select only the certificate (do not select the private key), and export it.
  2. In the Azure portal, click Browse All > App Services, and click your Mobile Apps back end. Under Settings, click App Service Push, and then click your notification hub name. Go to Apple Push Notification Services > Upload Certificate. Upload the .p12 file, selecting the correct Mode (depending on whether your client SSL certificate from earlier is production or sandbox). Save any changes.

Your service is now configured to work with push notifications on iOS.

Verify that your App ID matches your Cordova app

If the App ID you created in your Apple Developer Account already matches the ID of the widget element in config.xml, you can skip this step. However, if the IDs don't match, take the following steps:

  1. Delete the platforms folder from your project.
  2. Delete the plugins folder from your project.
  3. Delete the node_modules folder from your project.
  4. Update the id attribute of the widget element in config.xml to use the App ID that you created in your Apple Developer Account.
  5. Rebuild your project.
Test push notifications in your iOS app
  1. In Visual Studio, make sure that iOS is selected as the deployment target, and then choose Device to run on your connected iOS device.

    You can run on an iOS device connected to your PC using iTunes. The iOS Simulator does not support push notifications.

  2. Press the Run button or F5 in Visual Studio to build the project and start the app in an iOS device, then click OK to accept push notifications.

    Note

    The app requests confirmation for push notifications during the first run.

  3. In the app, type a task, and then click the plus (+) icon.

  4. Verify that a notification is received, then click OK to dismiss the notification.

(Optional) Configure and run on Windows

This section is for running the Apache Cordova app project on Windows 10 devices (the PhoneGap push plugin is supported on Windows 10). If you are not working with Windows devices, you can skip this section.

Register your Windows app for push notifications with WNS

To use the Store options in Visual Studio, select a Windows target from the Solution Platforms list, like Windows-x64 or Windows-x86 (avoid Windows-AnyCPU for push notifications).

  1. In Visual Studio Solution Explorer, right-click the Windows Store app project, and click Store > Associate App with the Store.

    Associate app with Windows Store

  2. In the wizard, click Next, and sign in with your Microsoft account. Type a name for your app in Reserve a new app name, and then click Reserve.
  3. After the app registration is successfully created, select the new app name, click Next, and then click Associate. This adds the required Windows Store registration information to the application manifest.
  4. Repeat steps 1 and 3 for the Windows Phone Store app project by using the same registration you previously created for the Windows Store app.
  5. Browse to the Windows Dev Center, and sign in with your Microsoft account. Click the new app registration in My apps, and then expand Services > Push notifications.
  6. On the Push notifications page, click Live Services site under Windows Push Notification Services (WNS) and Microsoft Azure Mobile Apps. Make a note of the values of the Package SID and the current value in Application Secret.

    App setting in the developer center

    Important

    The application secret and package SID are important security credentials. Do not share these values with anyone or distribute them with your app.

Watch a video showing similar steps

Configure the notification hub for WNS

  1. In the Azure portal, click Browse All > App Services, and click your Mobile Apps back end. Under Settings, click App Service Push, and then click your notification hub name.
  2. Go to Windows (WNS), enter the Security key (client secret) and Package SID that you obtained from the Live Services site, and then click Save.

    Set the WNS key in the portal

Your back end is now configured to use WNS to send push notifications.

Configure your Cordova app to support Windows push notifications

Open the configuration designer (right-click on config.xml and select View Designer), select the Windows tab, and choose Windows 10 under Windows Target Version.

To support push notifications in your default (debug) builds, open build.json file. Copy the "release" configuration to your debug configuration.

    "windows": {
        "release": {
            "packageCertificateKeyFile": "res\\native\\windows\\CordovaApp.pfx",
            "publisherId": "CN=yourpublisherID"
        }
    }

After the update, the build.json should contain the following code:

"windows": {
    "release": {
        "packageCertificateKeyFile": "res\\native\\windows\\CordovaApp.pfx",
        "publisherId": "CN=yourpublisherID"
        },
    "debug": {
        "packageCertificateKeyFile": "res\\native\\windows\\CordovaApp.pfx",
        "publisherId": "CN=yourpublisherID"
        }
    }

Build the app and verify that you have no errors. Your client app should now register for the notifications from the Mobile App backend. Repeat this section for every Windows project in your solution.

Test push notifications in your Windows app

In Visual Studio, make sure that a Windows platform is selected as the deployment target, such as Windows-x64 or Windows-x86. To run the app on a Windows 10 PC hosting Visual Studio, choose Local Machine.

Press the Run button to build the project and start the app.

In the app, type a name for a new todoitem, and then click the plus (+) icon to add it.

Verify that a notification is received when the item is added.

Next Steps

Learn how to use the SDKs.