在 Chrome 中通过服务-worker.js 全天候接收通知 24/7
Receive notifications 24/7 via service-worker.js in Chrome
我一直在做推送通知,
当我注册页面然后通过 curl 命令对其进行测试时,我收到了通知!
但是过了一段时间(可能1-2分钟),当我关闭推送通知范围已注册的选项卡,然后再次测试通知时,我无法收到通知。这种情况通常发生在 google Chrome 手机中。
我在这里做的解决方法是我需要先转到范围页面的页面,然后当我再次测试通知时,它现在可以工作了。虽然我不能这样做,因为我需要客户接收通知而无需一直在网站上。
这是我在 service worker 中的推送事件
self.addEventListener('push', function(event) {
var SOME_API_ENDPOINT = "https://somewhre.com/push_notification_api/service_worker_endpoint";
event.waitUntil(
fetch(SOME_API_ENDPOINT, {
method: 'post',
headers: {
"Content-type": "application/x-www-form-urlencoded; charset=UTF-8"
},
body: 'subscription_id=' + subscriptionId
}).then(function(response) {
return response.json().then(function(data) {
var title = data.notification.title;
var message = data.notification.message;
var icon = base + "assets/images/logo_notification.png";
var notificationTag = data.notification.url;
// var notificationTag = 'https://google.com'; //data.notification.tag;
return self.registration.showNotification(title, {
body: message,
icon: icon,
tag: notificationTag
});
});
})
);
});
即使我不在 SW 注册范围的页面中,我如何让我的服务人员全天候 24/7?
我需要使用 eventListeners 'install'、'activate' 和 'fetch' 吗?
Service Worker 似乎会持续存在但实际上不会 - 一个新实例会启动以响应事件。在移动设备上重启处理推送事件时会出现这种情况,但也有建议繁忙的 Service Worker 应该允许多个实例并行。
您的 subscriptionId
是一个全局参数,因此当您的 push
事件触发时它很可能是 undefined
。
要解决此问题,您需要将 subscriptionId
保留在某种存储中(可能是 IndexedDB)。
我还认为,为了让 service worker 持久化,它需要有一个 install
事件,并且该事件需要成功。
我一直在做推送通知, 当我注册页面然后通过 curl 命令对其进行测试时,我收到了通知!
但是过了一段时间(可能1-2分钟),当我关闭推送通知范围已注册的选项卡,然后再次测试通知时,我无法收到通知。这种情况通常发生在 google Chrome 手机中。
我在这里做的解决方法是我需要先转到范围页面的页面,然后当我再次测试通知时,它现在可以工作了。虽然我不能这样做,因为我需要客户接收通知而无需一直在网站上。
这是我在 service worker 中的推送事件
self.addEventListener('push', function(event) {
var SOME_API_ENDPOINT = "https://somewhre.com/push_notification_api/service_worker_endpoint";
event.waitUntil(
fetch(SOME_API_ENDPOINT, {
method: 'post',
headers: {
"Content-type": "application/x-www-form-urlencoded; charset=UTF-8"
},
body: 'subscription_id=' + subscriptionId
}).then(function(response) {
return response.json().then(function(data) {
var title = data.notification.title;
var message = data.notification.message;
var icon = base + "assets/images/logo_notification.png";
var notificationTag = data.notification.url;
// var notificationTag = 'https://google.com'; //data.notification.tag;
return self.registration.showNotification(title, {
body: message,
icon: icon,
tag: notificationTag
});
});
})
);
});
即使我不在 SW 注册范围的页面中,我如何让我的服务人员全天候 24/7?
我需要使用 eventListeners 'install'、'activate' 和 'fetch' 吗?
Service Worker 似乎会持续存在但实际上不会 - 一个新实例会启动以响应事件。在移动设备上重启处理推送事件时会出现这种情况,但也有建议繁忙的 Service Worker 应该允许多个实例并行。
您的 subscriptionId
是一个全局参数,因此当您的 push
事件触发时它很可能是 undefined
。
要解决此问题,您需要将 subscriptionId
保留在某种存储中(可能是 IndexedDB)。
我还认为,为了让 service worker 持久化,它需要有一个 install
事件,并且该事件需要成功。