推送通知即使在服务工作者中收到推送事件,也未显示

时间:2016-10-02 15:57:11

标签: push-notification google-cloud-messaging service-worker

自从过去15天以来,我一直在为服务工作者工作。它的学习速度非常快,但从那时起我就被困在我网站上的通知支持上。

我面临的问题是,即使在服务工作者注册的推送事件中收到通知,也不会显示通知。

但是当通过pushcrew.com等服务收到其他桌面通知时,会显示它,并且您点击其中的操作然后会显示我的通知。

   <!DOCTYPE html>
    <html>
    <head>
      <title></title>
      <link rel="manifest" href="./manifest.json">
   </head>
   <body>

<script type="text/javascript">
    window.onload = function(){
//    console.debug("Onload");

        navigator.serviceWorker
            .register('./service-worker.js')
            .then(function(registration){
                console.log("registration");

                registration.onupdatefound = function() {
                    var installingWorker = registration.installing;

                    installingWorker.onstatechange = function() {
                        switch (installingWorker.state) {
                            case 'installed':
                                if (navigator.serviceWorker.controller) {
                                    // At this point, the old content will have been purged and the fresh content will
                                    // have been added to the cache.
                                    // It's the perfect time to display a "New content is available; please refresh."
                                    // message in the page's interface.
                                    location.reload(true);
                                }
                                else {
                                    // At this point, everything has been precached.
                                    // It's the perfect time to display a "Content is cached for offline use." message.
                                }

                                break;
                            case 'redundant':
                                console.error('The installing service worker became redundant.');
                                break;
                            case 'activating':
                                console.log("activating");
                                break;
                            case 'activated':
                                registration.pushManager.subscribe({
                                    userVisibleOnly: true
                                }).then(function(sub) {
                                    console.log('endpoint:', sub.endpoint);
                                    document.write(sub.endpoint);

                                });
                                console.log("activated");
                                break;
                            default:
                                console.log("Default Condition" + installingWorker.state);
                                break;
                        }
                    }
                };

            })
            .catch(function(err){
//              alert("Service worker registration failed ");

            });


    }
</script>
</body>
</html>

的manifest.json

  {
"name": "WorkIndia",
"short_name": "WorkIndia",
"icons": [{
  "src": "icon-128x128.png",
    "sizes": "128x128",
    "type": "image/png"
  }, {
    "src": "icon-144x144.png",
    "sizes": "144x144",
    "type": "image/png"
  }, {
    "src": "icon-152x152.png",
    "sizes": "152x152",
    "type": "image/png"
  }, {
    "src": "icon-192x192.png",
    "sizes": "192x192",
    "type": "image/png"
  }, {
    "src": "icon-256x256.png",
    "sizes": "256x256",
    "type": "image/png"
  }],
"permissions": [
    "notifications"
  ],
"web_accessible_resources": [
  "icon-128x128.png"
],
"start_url": "index.html",
"display": "standalone",
"background_color": "#3E4EB8",
"theme_color": "#2F3BA2",
"gcm_sender_id": "234031710894"

}

服务worker.js

  'use strict';

  self.addEventListener('push', function(event) {
  //  if (self.skipWaiting) { self.skipWaiting(); }

  var notificationTitle = 'Hello';
  var notificationOptions = {
      body: 'Thanks for sending this push msg.',
      tag: 'simple-push-demo-notification',
      data: {
        url: 'https://developers.google.com/web/fundamentals/getting-started/push-notifications/'
      }
  };
  if (event.data) {
      const dataText = event.data.text();
      notificationTitle = 'Received Payload';
      notificationOptions.body = "Push data: " + dataText;
  }

  console.debug('Received a push message', event);

 event.waitUntil(
     self.registration.showNotification(notificationTitle, notificationOptions)
 );
});

self.addEventListener('notificationclick', function(event) {
console.log('On notification click: ', event.notification.tag);
// Android doesn’t close the notification when you click on it
// See: http://crbug.com/463146
event.notification.close();

// This looks to see if the current is already open and
// focuses if it is
event.waitUntil(clients.matchAll({
  type: 'window'
}).then(function(clientList) {
  for (var i = 0; i < clientList.length; i++) {
    var client = clientList[i];
    if (client.url === '/' && 'focus' in client) {
      return client.focus();
    }
  }
  if (clients.openWindow) {
    return clients.openWindow('/');
  }
}));
});

控制台

(index):16 registration
(index):41 activating
(index):51 activated
(index):47 endpoint: https://android.googleapis.com/gcm/send/coiKeSkPta0:APA91bGUTJD6TciT1HANKGd…HqUEz5iQY7y9I_BVbDbPWIv0r7zfHyhlwFl91odzSIhr71IPXDK4ie6ok3yWTN-pflj16Vezq5
service-worker.js:20 Received a push message PushEvent {data: null, type: "push", target: ServiceWorkerGlobalScope, currentTarget: ServiceWorkerGlobalScope, eventPhase: 2…}bubbles: falsecancelBubble: falsecancelable: falsecomposed: falsecurrentTarget: ServiceWorkerGlobalScopedata: nulldefaultPrevented: falseeventPhase: 0path: Array[0]returnValue: truesrcElement: ServiceWorkerGlobalScopetarget: ServiceWorkerGlobalScopetimeStamp: 0type: "push"__proto__: PushEvent

1 个答案:

答案 0 :(得分:1)

您拥有notifications的权限,但不能使用gcm。这可能是您遇到问题的原因。

您必须在权限列表中添加gcm(如GCM Documentation所示)。

"permissions": [
    "gcm", ... // Other permissions, like "storage"
]

此外,由于event功能已经是回调,因此我认为无需使用waitUntilshowNotification。只需在console.debug之后调用该函数,它也可以帮助解决问题。