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

前端 未结 6 434
一向
一向 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:24

    @gauchofunky's answer is correct. With some guidance from the folks on the Chromium dev slack channel and @gauchofunky I was able to piece something together. Here's how to work around the current limitations; hopefully my answer becomes obsolete soon!

    First figure out how you're going to persist notifications on your backend. I'm using Node/Express and MongoDB with Mongoose and my schema looks like this:

    var NotificationSchema = new Schema({
      _user: {type: mongoose.Schema.Types.ObjectId, ref: 'User'},
      subscriptionId: String,
      title: String,
      body: String,
      sent: { type: Boolean, default: false }
    });
    

    Be sure to add an icon if you'd like to alter the icon. I use the same icon every time so mine's hardcoded in the service worker.

    Figuring out the correct REST web service took some thought. GET seemed like an easy choice but the call to get a notification causes side effects, so GET is out. I ended up going with a POST to /api/notifications with a body of {subscriptionId: }. Within the method we basically perform a dequeue:

    var subscriptionId = req.body.subscriptionId;
    
    Notification
    .findOne({_user: req.user, subscriptionId: subscriptionId, sent: false})
    .exec(function(err, notification) {
      if(err) { return handleError(res, err); }
      notification.sent = true;
      notification.save(function(err) {
        if(err) { return handleError(res, err); }
        return res.status(201).json(notification);
      });
    });
    

    In the service worker we need to for sure get the subscription before we make the fetch.

    self.addEventListener('push', function(event) {
      event.waitUntil(
        self.registration.pushManager.getSubscription().then(function(subscription) {
          fetch('/api/notifications/', {
            method: 'post',
            headers: {
              'Authorization': 'Bearer ' + self.token,
              'Accept': 'application/json',
              'Content-Type': 'application/json'
            },
            body: JSON.stringify(subscription)
          })
          .then(function(response) { return response.json(); })
          .then(function(data) {
            self.registration.showNotification(data.title, {
              body: data.body,
              icon: 'favicon-196x196.png'
            });
          })
          .catch(function(err) {
            console.log('err');
            console.log(err);
          });
        })
      );
    });
    

    It's also worth noting that the subscription object changed from Chrome 43 to Chrome 45. In Chrome 45 the subscriptionId property was removed, just something to look out for - this code was written to work with Chrome 43.

    I wanted to make authenticated calls to my backend so I needed to figure out how to get the JWT from my Angular application to my service worker. I ended up using postMessage. Here's what I do after registering the service worker:

    navigator.serviceWorker.register('/service-worker.js', {scope:'./'}).then(function(reg) {
      var messenger = reg.installing || navigator.serviceWorker.controller;
      messenger.postMessage({token: $localStorage.token});
    }).catch(function(err) {
      console.log('err');
      console.log(err);
    });
    

    In the service worker listen for the message:

    self.onmessage.addEventListener('message', function(event) {
      self.token = event.data.token;
    });
    

    Strangely enough, that listener works in Chrome 43 but not Chrome 45. Chrome 45 works with a handler like this:

    self.addEventListener('message', function(event) {
      self.token = event.data.token;
    });
    

    Right now push notifications take quite a bit of work to get something useful going - I'm really looking forward to payloads!

提交回复
热议问题