订阅用户失败:DOMException:订阅失败 - 没有活动的Service Worker

时间:2017-02-06 08:09:29

标签: javascript push-notification service-worker

我正在尝试从代码实验室谷歌学习,但我在实施时遇到了错误。

这是我的代码。

服务人员的注册

 if ('serviceWorker' in navigator && 'PushManager' in window) {
  console.log('Service Worker and Push is supported');

  navigator.serviceWorker.register('sw.js')
  .then(function(swReg) {
    console.log('Service Worker is registered', swReg);

    swRegistration = swReg;
  })
  .catch(function(error) {
    console.error('Service Worker Error', error);
  });
} else {
  console.warn('Push messaging is not supported');
  pushButton.textContent = 'Push Not Supported';
}

在此代码段中我收到了错误

function subscribeUser() {
  const applicationServerKey = urlB64ToUint8Array(applicationServerPublicKey);
  swRegistration.pushManager.subscribe({
    userVisibleOnly: true,
    applicationServerKey: applicationServerKey
  })
  .then(function(subscription) {
    console.log('User is subscribed.');

    updateSubscriptionOnServer(subscription);

    isSubscribed = true;

    updateBtn();
  })
  .catch(function(err) {
    console.log('Failed to subscribe the user: ', err);
    updateBtn();
  });
}

console.log('无法订阅用户:',错误); 这里我收到错误:订阅用户失败:DOMException:订阅失败 - 没有活动的服务工作者

2 个答案:

答案 0 :(得分:0)

在Chrome Inspect / Application / Service Works中取消选中网络旁路 为我工作!

答案 1 :(得分:0)

如果还有人想知道……使用 async/await:

  // Registering Service Worker
  const serviceWorkerRegistration = await navigator.serviceWorker.register('./sw.js', { scope:'./' })
  .catch((err) => { return console.log('[Service Worker] Registration Error:', err) })
  console.log('[Service Worker] Registered. Scope:', serviceWorkerRegistration.scope)

  await navigator.serviceWorker.ready; // Here's the waiting

  // Registering push
  const subscription = await serviceWorkerRegistration.pushManager.subscribe({
    userVisibleOnly: true,
    applicationServerKey: urlBase64ToUint8Array(publicVapidKey)
  })
  .catch((err) => { return console.log('[Web Push] Registration Error:', err) });
  console.log('[Web Push] Registered');