Sending data / payload to the Google Chrome Push Notification with Javascript

前端 未结 6 427
一向
一向 2020-12-02 14:49

I\'m working on the Google Chrome Push Notification and I\'m trying to send the payload to the google chrome worker but, I have no idea how I receive this payload.

I

6条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-02 15:15

    Follow these steps to achieve this:

    In the browser:

    You need to get the subscription object and save it, so your server has access to it: Read more about it

    navigator.serviceWorker.ready.then(serviceWorkerRegistration => {
                serviceWorkerRegistration.pushManager.subscribe({userVisibleOnly: true})
                  .then(subscription => {
                      //save subscription.toJSON() object to your server
        })});
    

    In the server:

    install web-push npm package

    And send a web push like this:

        const webpush = require('web-push');
    
    
        setImmediate(async () => {
    
          const params = {
            payload: {title: 'Hey', body: 'Hello World'}
          };
          //this is the subscription object you should get in the browser. This is a demo of how it should look like
          const subscription = {"endpoint":"https://android.googleapis.com/gcm/send/deC24xZL8z4:APA91bE9ZWs2KvLdo71NGYvBHGX6ZO4FFIQCppMsZhiTXtM1S2SlAqoOPNxzLlPye4ieL2ulzzSvPue-dGFBszDcFbSkfb_VhleiJgXRA8UwgLn5Z20_77WroZ1LofWQ22g6bpIGmg2JwYAqjeca_gzrZi3XUpcWHfw","expirationTime":null,"keys":{"p256dh":"BG55fZ3zZq7Cd20vVouPXeVic9-3pa7RhcR5g3kRb13MyJyghTY86IO_IToVKdBmk_2kA9znmbqvd0-o8U1FfA3M","auth":"1gNTE1wddcuF3FUPryGTZOA"}};
    
          if (subscription.keys) {
            params.userPublicKey = subscription.keys.p256dh;
            params.userAuth      = subscription.keys.auth;
          }
    
    // this key you should take from firebase console for example
    // settings -> cloud messaging -> Server key     
    webpush.setGCMAPIKey('AAAASwYmslc:APfA91bGy3tdKvuq90eOvz4AoUm6uPtbqZktZ9dAnElrlH4gglUiuvereTJJWxz8_dANEQciX9legijnJrxvlapI84bno4icD2D0cdVX3_XBOuW3aWrpoqsoxLDTdth86CjkDD4JhqRzxV7RrDXQZd_sZAOpC6f32nbA');
    
          try {
            const r = await webpush.sendNotification(subscription, JSON.stringify(params));
            console.log(r);
          }
          catch (e) {
            console.error(e);
          }
        });
    

提交回复
热议问题