无法获取 serviceWorkerRegistration

Posted

技术标签:

【中文标题】无法获取 serviceWorkerRegistration【英文标题】:Unable to get serviceWorkerRegistration 【发布时间】:2016-09-27 11:51:39 【问题描述】:

我关注了tutorial,使用 GCM 在 Google Chrome 上进行推送通知。我的问题是我无法完成操作!我不知道为什么。

在订阅函数中,它会在尝试执行时中断该函数

navigator.serviceWorker.ready.then(function(serviceWorkerRegistration)   
    serviceWorkerRegistration.pushManager.subscribe()  
        .then(function(subscription)  
            // ...
        ;
);       

没有控制台错误,没有控制台警告,也没有进入catch!这是我所做的:

function subscribe()   

  var pushButton = document.querySelector('.js-push-button');  
  pushButton.disabled = true;

  navigator.serviceWorker.ready.then(function(serviceWorkerRegistration)   
    serviceWorkerRegistration.pushManager.subscribe()  
      .then(function(subscription)   

        // The subscription was successful
        isPushEnabled = true;  
        pushButton.textContent = 'Disable Push Messages';  
        pushButton.disabled = false;
        console.log("sending sub");
        sendSubscriptionToServer(subscription);
        // TODO: Send the subscription.endpoint to your server
        // and save it to send a push message at a later date
        return sendSubscriptionToServer(subscription);  
      )  
      .catch(function(e)   
        if (Notification.permission === 'denied')   
          // The user denied the notification permission which
          // means we failed to subscribe and the user will need
          // to manually change the notification permission to
          // subscribe to push messages
          console.warn('Permission for Notifications was denied');  
          pushButton.disabled = true;  
         else   
          // A problem occurred with the subscription; common reasons
          // include network errors, and lacking gcm_sender_id and/or
          // gcm_user_visible_only in the manifest.
          console.error('Unable to subscribe to push.', e);  
          pushButton.disabled = false;  
          pushButton.textContent = 'Enable Push Messages';  
          
      );  
  );  

【问题讨论】:

请先尝试注册您的 Service Worker,因为这是使用它的第一步。这个GitHub post 可能有助于更好地了解服务人员。 【参考方案1】:

唯一对我有用的是“getRegistration”方法,用作以下代码

navigator.serviceWorker.getRegistration('/Workers/').then( r => subscribe( r ) );

其中 '/Workers/' 是 ServiceWorker.js 所在的路径

【讨论】:

以上是关于无法获取 serviceWorkerRegistration的主要内容,如果未能解决你的问题,请参考以下文章

远程通知不会触发notificationclick

navigator.serviceWorker 从未准备好

PWA - beforeinstallprompt 未调用

Javascript Service Worker onload 显示通知

ServiceWorkerContainer.ready 为特定的 scriptURL 准备好了吗?

我们可以在 ios serviceworker 上运行 firebase 实时监听吗?