我试图订阅用户,但这是我第一次收到的错误。 第二次,它正在工作,因为用户已经激活
这是我的代码:
if ('serviceWorker' in navigator) {
console.log('Service Worker is supported');
navigator.serviceWorker.register('sw.js').then(function(reg) {
console.log(':^)', reg);
reg.pushManager.subscribe({
userVisibleOnly: true
}).then(function(sub) {
console.log('endpoint:', sub.endpoint);
var div = document.getElementById('id');
div.innerHTML = div.innerHTML + sub.endpoint;
// var b = document.getElementsByTagName('body')[0];
//b.appendChild(div);
//alert(sub.endpoint);
});
});
}
我已经尝试过以下操作,但ready.then()
方法没有发生:
if ('serviceWorker' in navigator) {
console.log('Service Worker is supported');
navigator.serviceWorker.register('sw.js').then(function(sreg) {
console.log(':^)', sreg);
navigator.serviceWorker.ready.then(function(reg) {
reg.pushManager.subscribe({
userVisibleOnly: true
}).then(function(sub) {
console.log('endpoint:', sub.endpoint);
var div = document.getElementById('id');
div.innerHTML = div.innerHTML + sub.endpoint;
// var b = document.getElementsByTagName('body')[0];
//b.appendChild(div);
//alert(sub.endpoint);
});
});
});
}
有什么想法吗?
答案 0 :(得分:7)
您应该在触发订阅之前等待服务工作者被激活。
使用stateChange侦听器来确定服务工作者是否处于活动状态
navigator.serviceWorker.register(workerFileName, {scope: "/"})
.then(
function (reg) {
var serviceWorker;
if (reg.installing) {
serviceWorker = reg.installing;
// console.log('Service worker installing');
} else if (reg.waiting) {
serviceWorker = reg.waiting;
// console.log('Service worker installed & waiting');
} else if (reg.active) {
serviceWorker = reg.active;
// console.log('Service worker active');
}
if (serviceWorker) {
console.log("sw current state", serviceWorker.state);
if (serviceWorker.state == "activated") {
//If push subscription wasnt done yet have to do here
console.log("sw already activated - Do watever needed here");
}
serviceWorker.addEventListener("statechange", function(e) {
console.log("sw statechange : ", e.target.state);
if (e.target.state == "activated") {
// use pushManger for subscribing here.
console.log("Just now activated. now we can subscribe for push notification")
subscribeForPushNotification(reg);
}
});
}
},
function (err) {
console.error('unsuccessful registration with ', workerFileName, err);
}
);
答案 1 :(得分:1)
您可以通过检查服务工作者状态来解决此问题。仅在服务工作人员处于活动状态时执行您的操作。
navigator.serviceWorker.register('sw.js').then(function(reg) {
if(reg.installing) {
console.log('Service worker installing');
} else if(reg.waiting) {
console.log('Service worker installed');
} else if(reg.active) {
console.log('Service worker active');
}
// Include below mentioned validations
}
支持或不支持使用
检查推送 // Check if push messaging is supported
if (!('PushManager' in window)) {
console.log('Push messaging isn\'t supported.');
return;
}
//
if (Notification.permission === 'denied') {
console.log('The user has blocked notifications.');
return;
}
在这两项检查后实现您的功能。
navigator.serviceWorker.ready.then(function(reg) { .... })
希望这有帮助