【问题标题】:Unable to get serviceWorkerRegistration无法获取 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 可能有助于更好地了解服务人员。

标签: javascript push-notification google-cloud-messaging


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-01-15
    • 1970-01-01
    • 1970-01-01
    • 2023-03-25
    • 2014-09-05
    • 2021-12-26
    • 2015-05-11
    相关资源
    最近更新 更多