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

roh*_*ash 5 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';
}
Run Code Online (Sandbox Code Playgroud)

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

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();
  });
}
Run Code Online (Sandbox Code Playgroud)

console.log('订阅用户失败:', err); 在这里我收到错误:无法订阅用户:DOMException:订阅失败 - 没有活动的 Service Worker

小智 -2

在 Chrome 检查/应用程序/服务工作中取消选中绕过网络对我有用!