Setting Up Azure Push Notifications To Chrome Client

Here in this article I will describe what PushNotification is and what setting is required to set PushNotification Hub in Azure and send PushNotification to Chrome client.
 
Here I will describe the following things in detail:
  1. Enabling Google Cloud Messaging.
  2. Creating a Notification Hub in Azure.
  3. Configuring the Notification Hub with the Chrome APP
  4. Creating a chrome App for receiving Push Notification. (This is for installing in chrome for getting PushNotification).
  5. Installing the Chrome App.
  6. Sending Notification to Chrome App.
In this article I will cover the above mentioned topics one by one. Firstly, I will enable the Google cloud Messaging as follows.

Enabling Google Client Messaging.

To enable  Google client messaging we have to follow the following steps in Google Cloud Console.Login to the Google cloud console, You will find the following screen.


Now In the Dashboard, click the MyProject and create a new project as follows.

 

Now it will ask for the name of the project. Give a meaningful name to the project as follows.

 

After clicking the
Create button the project with the given name created which you will see in the dashboard. After this go to Google APIs tab and click that.

 

After that search for Google cloud Messaging for Android, iPhone and Chrome in the search bar.



Now you will find the following screen, first of all click the button to enable this.

 

Now, go for credentials and select the following option on the screen:

 

Now, save the senderId that is Project ID.



Now, click to create API Key and after that you will get the key. Now copy the api key, this key is needed to configure the Hub in the Azure.



Now, copy the credentials and save the sender Id. So,in this way we can get the API key in Google Cloud Messaging.

Creating a notification hub in Azure

After creating the the API key successfully now we need to create an Azure Hub, where we can use this API key to get the connection string. So, the steps to create the Hub are shown below.

Login to your azure portal by providing correct credentials.



Click Browse, search for Service Bus,



Now click the Service Namespace it will ask for your credential and will land you in Service Bus Page.

Here click on  Service Bus, Notification Hub, then click Quick Create. Type a name for your notification hub, and then click Create a new Notification Hub.

I have created ChromeNotification as follows.



Click on it, you will find the following DashBoard.



Now, click the CONFIGURE tab at the top as follows.



Now scroll down and go up to Google cloud messaging and here you put the API key that you get from Google Cloud Messaging.



Now after entering the key save this and and go to the dashboard and click the CONNECTION INFORMATION.



Now you will get the following connection string, just copy both of them.

So, in this way we are able to configure the Notification Hub. Now the main thing is to create a Chrome Extension.

Create and Configure the Notification Hub with the Chrome APP

This is the third step towards reaching our destination, because of this Chrome app we will receive push notifications. If you are not aware of how to create a Chrome app you should reach this document below. Here, it is nicely explained how to create a Chrome app.
Here it is clearly explained about creating Chrome app and what are the things used for creating it. To create this I have used the following things.
  1. manifest.json
  2. register.js
  3. background.js
  4. register.html
  5. gcm_128.png

    As we know manifest and background for a chrome app is mandatory, here i have written the code for these instead. Just copy and paste , otherwise this is already available on GitHub.

    Open a notepad and copy the mainfest.json and save it.
    1. {  
    2.   "name""GCM Notifications",  
    3.   "description""Chrome platform app.",  
    4.   "manifest_version": 2,  
    5.   "version""0.1",  
    6.   "app": {  
    7.     "background": {  
    8.       "scripts": ["background.js"]  
    9.     }  
    10.   },  
    11.   "permissions": ["gcm""storage""notifications"],  
    12.   "icons": { "128""gcm_128.png" }  
    13. }  
    Same for register.js Open the notepad and save it.
    1. var registrationId = "";  
    2.   
    3. function setStatus(status) {  
    4.   document.getElementById("status").innerHTML = status;  
    5. }  
    6.   
    7. function register() {  
    8.   var senderId = document.getElementById("senderId").value;  
    9.   chrome.gcm.register([senderId], registerCallback);  
    10.   
    11.   setStatus("Registering ...");  
    12.   
    13.   // Prevent register button from being click again before the registration  
    14.   // finishes.  
    15.   document.getElementById("register").disabled = true;  
    16. }  
    17.   
    18. function registerCallback(regId) {  
    19.   registrationId = regId;  
    20.   document.getElementById("register").disabled = false;  
    21.   
    22.   if (chrome.runtime.lastError) {  
    23.     // When the registration fails, handle the error and retry the  
    24.     // registration later.  
    25.     setStatus("Registration failed: " + chrome.runtime.lastError.message);  
    26.     return;  
    27.   }  
    28.   
    29.   setStatus("Registration succeeded. Please run the following command to send a message.");  
    30.   
    31.   // Mark that the first-time registration is done.  
    32.   chrome.storage.local.set({registered: true});  
    33.   
    34.   // Format and show the curl command that can be used to post a message.  
    35.   updateCurlCommand();  
    36. }  
    37.   
    38. function updateCurlCommand() {  
    39.   var apiKey = document.getElementById("apiKey").value;  
    40.   if (!apiKey)  
    41.     apiKey = "YOUR_API_KEY";  
    42.   
    43.   var msgKey = document.getElementById("msgKey").value;  
    44.   if (!msgKey)  
    45.     msgKey = "YOUR_MESSAGE_KEY";  
    46.   
    47.   var msgValue = document.getElementById("msgValue").value;  
    48.   if (!msgValue)  
    49.     msgValue = "YOUR_MESSAGE_VALUE";  
    50.   
    51.   var command = 'curl' +  
    52.       ' -H "Content-Type:application/x-www-form-urlencoded;charset=UTF-8"' +  
    53.       ' -H "Authorization: key=' + apiKey + '"' +  
    54.       ' -d "registration_id=' + registrationId + '"' +  
    55.       ' -d data.' + msgKey + '=' + msgValue +  
    56.       ' https://android.googleapis.com/gcm/send';  
    57.   document.getElementById("console").innerText = command;  
    58. }  
    59.   
    60. window.onload = function() {  
    61.   document.getElementById("register").onclick = register;  
    62.   document.getElementById("apiKey").onchange = updateCurlCommand;  
    63.   document.getElementById("msgKey").onchange = updateCurlCommand;  
    64.   document.getElementById("msgValue").onchange = updateCurlCommand;  
    65.   setStatus("You have not registered yet. Please provider sender ID and register.");  
    66. }  
    Now open Notepad and copy the background.js and save it.
    1. // Returns a new notification ID used in the notification.  
    2. function getNotificationId() {  
    3.   var id = Math.floor(Math.random() * 9007199254740992) + 1;  
    4.   return id.toString();  
    5. }  
    6.   
    7. function messageReceived(message) {  
    8.   // A message is an object with a data property that  
    9.   // consists of key-value pairs.  
    10.   
    11.   // Concatenate all key-value pairs to form a display string.  
    12.   var messageString = "";  
    13.   for (var key in message.data) {  
    14.     if (messageString != "")  
    15.       messageString += ", "  
    16.     messageString += key + ":" + message.data[key];  
    17.   }  
    18.   console.log("Message received: " + messageString);  
    19.   
    20.   // Pop up a notification to show the GCM message.  
    21.   chrome.notifications.create(getNotificationId(), {  
    22.     title: 'GCM Message',  
    23.     iconUrl: 'gcm_128.png',  
    24.     type: 'basic',  
    25.     message: messageString  
    26.   }, function() {});  
    27. }  
    28.   
    29. var registerWindowCreated = false;  
    30.   
    31. function firstTimeRegistration() {  
    32.   chrome.storage.local.get("registered"function(result) {  
    33.     // If already registered, bail out.  
    34.     if (result["registered"])  
    35.       return;  
    36.   
    37.     registerWindowCreated = true;  
    38.     chrome.app.window.create(  
    39.       "register.html",  
    40.       {  width: 500,  
    41.          height: 400,  
    42.          frame: 'chrome'  
    43.       },  
    44.       function(appWin) {}  
    45.     );  
    46.   });  
    47. }  
    48.   
    49. // Set up a listener for GCM message event.  
    50. chrome.gcm.onMessage.addListener(messageReceived);  
    51.   
    52. // Set up listeners to trigger the first time registration.  
    53. chrome.runtime.onInstalled.addListener(firstTimeRegistration);  
    54. chrome.runtime.onStartup.addListener(firstTimeRegistration);  
    Now copy the register.html and paste it as follows.
    1. <html>  
    2.   
    3. <head>  
    4. <title>GCM Registration</title>  
    5. <script src="register.js"></script>  
    6. </head>  
    7.   
    8. <body>  
    9.   
    10. Sender ID:<input id="senderId" type="TEXT" size="20"><br/>  
    11. <button id="register">Register</button>  
    12. <br/><br/>  
    13.   
    14. <div id="status" style="background-color:#e5e5e5;padding:5px">  
    15. </div>  
    16. <br/>  
    17.   
    18. API Key:<input id="apiKey" type="TEXT" size="30"><br/>  
    19. Message: Key<input id="msgKey" type="TEXT" size="20">   Value<input id="msgValue" type="TEXT" size="20">  
    20.   
    21. <textarea id="console" type="TEXT" readonly style="width:460px;height:210px;"></textarea>  
    22.   
    23. </body>  
    24.   
    25. </html>  
    Now, add an image gcm_128 which should be 128*128.



    Save all these contents in a folder and rename it as gcm-notifications. Here is my folder,


           Installing the chrome App
  1. Open the chrome browser and click the following settings.



    After clicking Extension it will show the following things.



    Click the Load unpacked extension and browse your folder. It will upload the chrome app as in the following:



    Now it will show the popup.



    Now add the Sender Id you get and click register to get the register_id.



    Now, copy the "registration_id" and launch the Rest Client and provide the appropriate details to send the Push Notification.


    Now, you can check if it will send a push notification with the following message.



    Thus in this way you can send Push Notifications to google Chrome client.
Read more articles on Azure: