Posting data with GCM push notification

2019-02-18 16:27发布

I'm trying out the GCM push notification API. So far it works fine, but I'm not sure how to post additional data.

I followed the steps on this page: https://developers.google.com/web/fundamentals/getting-started/push-notifications/step-07

So I ended up writing a curl request like this:

curl --header "Authorization: key=myKey" --header "Content-Type: application/json" https://android.googleapis.com/gcm/send -d "{\"registration_ids\":[myRegistrationId], \"additionalData\": {\"user_id\":\"1\"}}"

And then my sw.js (my service worker)

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

Is there a way to read out the additionalData in this event? Or am I not supposed to do it like this?

Thanks for reading!

2条回答
甜甜的少女心
2楼-- · 2019-02-18 16:32

I followed this step and did not change anything.

I tried POST with cURL:

curl --request POST --url localhost:8080/api/send-push-msg --header 'content-type: application/json' --data '{"subscription":{"endpoint":"https://fcm.googleapis.com/fcm/send/fKr7EsvRiyA:APA.....[Changes with your data]","keys":{"p256dh":"Your Key","auth":"Your Auth"}},"data":"Your Messages Here","applicationKeys":{"public":"Your Public Key Server","private":"Private Key Server"}}'

It worked well for me. :)

查看更多
ら.Afraid
3楼-- · 2019-02-18 16:49

I would suggest using one of the libraries in https://github.com/web-push-libs, they hide the complexity associated with push payloads and they support both the standard web push protocol (currently supported by Firefox and soon used by default in Chrome) and the proprietary GCM protocol (which will be deprecated in Chrome sooner or later).

Currently there are libraries for Node.js, PHP, Python and Java.

查看更多
登录 后发表回答