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

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

    To retrieve that data, you need to parse "event.data.text()" to a JSON object. I'm guessing something was updated since you tried to get this to work, but it works now. Unlucky!

    However, since I made it to this post when searching for a solution myself, others would probably like a working answer. Here it is:

    // Push message event handler
    self.addEventListener('push', function(event) {
    
      // If true, the event holds data
      if(event.data){
    
        // Need to parse to JSON format
        // - Consider event.data.text() the "stringify()"
        //   version of the data
        var payload = JSON.parse(event.data.text());
        // For those of you who love logging
        console.log(payload); 
    
        var title = payload.data.title;
        var body  = payload.data.body;
        var icon  = './assets/icons/icon.ico'
        var tag   = 'notification-tag';
    
        // Wait until payload is fetched
        event.waitUntil(
          self.registration.showNotification(title, {
            body: body,
            icon: icon,
            tag: tag,
            data: {} // Keeping this here in case I need it later
          })
        );
    
      } else {
        console.log("Event does not have data...");
      }
    
    }); // End push listener
    
    // Notification Click event
    self.addEventListener('notificationclick', function(event) {
      console.log("Notification Clicked");
    }); // End click listener
    

    Personally, I will be creating a "generic" notification in case my data is funky, and will also be using try/catch. I suggest doing the same.

提交回复
热议问题