Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Desktop push notification using Google cloud messaging and service worker

I want to send push notification to all my desktop users using google cloud messaging

I completed following steps successfully

  • Initialised in service worker
  • Created a project on the Google Developers Console
  • Added a manifest
  • sent using php CURL

Here is my CURL commands

$url = 'https://android.googleapis.com/gcm/send';
$msg="hi";
$data = array('title'=> $msg,'message'=>'Hello');
$regids= // added regids;
$fields = array('to' => $regids,'data' => $data);
$headers = array( 'Authorization: My auth key','Content-Type: application/json');

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));

print_r(json_encode($fields));
$result=curl_exec($ch);
echo $result; 
if($result==FALSE)
{
    die('Curl Failed');
}
curl_close($ch);

Everything is working fine and I am able to display a default notification using the following code

self.addEventListener('push', function(event) {
  console.log('Push message', event);
  var title = 'Push message';
  event.waitUntil(
    self.registration.showNotification(title, {
      body: 'The Message',
      icon: 'images/icon.png',
      tag: 'my-tag'
    }));
});

But what I need is to display the notification message which I sent through CURL command (In app we can do that easily)

I got the following code for receiving the push notification (google)

self.addEventListener('push', function(event) {  
  // Since there is no payload data with the first version  
  // of push messages, we'll grab some data from  
  // an API and use it to populate a notification  
  event.waitUntil(  
    fetch(SOME_API_ENDPOINT).then(function(response) {  
      if (response.status !== 200) {  
        // Either show a message to the user explaining the error  
        // or enter a generic message and handle the
        // onnotificationclick event to direct the user to a web page  
        console.log('Looks like there was a problem. Status Code: ' + response.status);  
        throw new Error();  
      }

      // Examine the text in the response  
      return response.json().then(function(data) {  
        if (data.error || !data.notification) {  
          console.error('The API returned an error.', data.error);  
          throw new Error();  
        }  

        var title = data.notification.title;  
        var message = data.notification.message;  
        var icon = data.notification.icon;  
        var notificationTag = data.notification.tag;

        return self.registration.showNotification(title, {  
          body: message,  
          icon: icon,  
          tag: notificationTag  
        });  
      });  
    }).catch(function(err) {  
      console.error('Unable to retrieve data', err);

      var title = 'An error occurred';
      var message = 'We were unable to get the information for this push message';  
      var icon = URL_TO_DEFAULT_ICON;  
      var notificationTag = 'notification-error';  
      return self.registration.showNotification(title, {  
          body: message,  
          icon: icon,  
          tag: notificationTag  
        });  
    })  
  );  
});

It always displays

We were unable to get the information for this push message

What is the SOME_API_ENDPOINT mentioned in that code ?
I tried with https://android.googleapis.com/gcm/send instead of endpoint and also with user endpoints in service worker but not working .

Any Help is much Appreciated

like image 537
Sree KS Avatar asked Jul 12 '16 13:07

Sree KS


People also ask

How do I send a push notification to Google Assistant?

Use the following code to get an access token from the service account key and send a push notification: // Use the Actions API to send a Google Assistant push notification. A mobile ads SDK for AdMob publishers who are building apps on Unity.

How do I get notifications when a push is received?

When you trigger a push message, the browser receives the push message, figures out what service worker the push is for, wakes up that service worker, and dispatches a push event. You need to listen for this event and show a notification as a result. console. log ( ' [Service Worker] Push Received.' ); Let's step through this code.

What is PushPush messaging?

Push messaging provides a simple and effective way to re-engage with your users. In this codelab, you'll learn how to add push notifications to your web app.

What is the use case of service workers in push notifications?

This basic script listens for push events and displays them when the push comes. One of the use case of service workers’ is push notification yes, but not only. There are so many things you can do with service workers, like caching files, mocking data etc. See the Google Reference for service worker lifecycle.


1 Answers

As far as I know, SOME_API_ENDPOINT mentioned is an API backend which is used to simplify client access to data from other applications.

As discussed in Overview of Cloud Endpoints,

Google Cloud Endpoints consists of tools, libraries and capabilities that allow you to generate APIs and client libraries from an App Engine application, referred to as an API backend, to simplify client access to data from other applications. Endpoints makes it easier to create a web backend for web clients and mobile clients such as Android or Apple's iOS.

More information on the use of endpoints are completely discussed in Best practices for Google Cloud Endpoints such as, how to create your App Engine backend.

You may also use this SO post - Google endpoints and Google Cloud Messaging as one of your references which can help.

like image 85
Teyam Avatar answered Nov 04 '22 08:11

Teyam