网络推送 - 放置服务工作者

时间:2016-12-02 13:36:08

标签: push-notification push service-worker web-push

从这里https://developers.google.com/web/fundamentals/getting-started/primers/service-workers

  1. 如果服务工作者位于域的 root ,则表示这意味着 服务工作者的范围将是整个起源。
  2. 但是如果我们在/example/sw.js注册服务工作者文件,那么 服务工作者只能看到获取事件的页面 URL以/ example /开头(即/ example / page1 /,/ example / page2 /)。
  3. 如果我将服务工作者放在/ example /中,则第二点仅提及 fetch 不能在/(root或示例)下工作。

    但是,如果服务工作者位于/ example /并且网页位于/(根目录或示例),那么订阅(生成子对象)本身就不会生成显然没有解释。

    请告诉我,即使服务工作者本身的订阅(pushManager.getSubscription)生成也不会发生。

    PS:我在Chrome 54.0.2840.100上尝试过Ubuntu 16.04 LTS

1 个答案:

答案 0 :(得分:0)

生成订阅对象不依赖于服务工作者范围。

可以在任何地方进行

EG。 permission.js

export function allowNotifications(scope){
  if (navigator.serviceWorker && Notification){
    if( Notification.permission !== "granted") {
      navigator.serviceWorker.ready.then(function(reg) {
        subscribe(reg);
      });
    }
  }
}

function subscribe(reg) {
     reg.pushManager.subscribe({userVisibleOnly: true}).then(function(pushSubscription) {
          bindUserToDevice(JSON.stringify(pushSubscription));
     }, function (err) {
        console.log('error');
      });
}

export function bindUserToDevice(subscriptionObj) {

  // received subsciption object should be send to backend to bind the device for pushes
  var data = {
    type: 'POST',
    url : '/bind',
    body: subscriptionObj,
  };
  fetch('/bind', data);

}
可以从任何地方调用

allowNotifications 功能。只有服务工作者文件应存在于root上,该文件应具有推送事件

 global.addEventListener('push', function(event) {
    var pushObj = event.data.json();
    var pushData = pushObj.data;

    var title = pushData && pushData.title;
    var body = pushData && pushData.body;
    var icon = '/img/logo.png';

    event.waitUntil(global.registration.showNotification(title, {
        body: body,
        icon: icon,
        data:pushData
    }));
});
相关问题