[英]Failed to subscribe the user: DOMException: Subscription failed - no active Service Worker
I am trying to learn from code lab google but I got an error while implementing it.我正在尝试从谷歌代码实验室学习,但在实现它时出现错误。
here is my code.这是我的代码。
Registration of 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';
}
in this code snippet I got error在这个代码片段中我得到了错误
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('Failed to subscribe the user: ', err); console.log('订阅用户失败:', err); here I got error : Failed to subscribe the user: DOMException: Subscription failed - no active Service Worker在这里我收到错误:无法订阅用户:DOMException:订阅失败 - 没有活动的 Service Worker
If anyone is still wondering... using async/await:如果有人仍然想知道……使用 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');
在 Chrome Inspect / Application / Service Works 中取消选中绕过网络为我工作!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.