在为 Chrome 处理 GCM 推送通知时,我已经为服务工作人员收到 GCM 推送事件设置了推送通知。
我正在发起服务调用。该服务返回一个数据对象,其中我有一个 URL,我想在用户单击通知时打开该 URL
这是我目前的代码。
Var urlOpen = null;
self.addEventListener('push', function(event) {
event.waitUntil(
fetch(serviceLink).then(function(response) {
if (response.status !== 200) {
console.log('Looks like there was a problem. Status Code: ' +
response.status);
throw new Error();
}
return response.json().then(function(data) {
console.log(data);
var title = data.title;
var body = data.desc;
var icon = data.image;
var tag = 'notification tag';
urlOpen = data.clickUrl;
return self.registration.showNotification(title, {
body: body,
icon: icon,
tag: tag
})
});
})
);
});
self.addEventListener('notificationclick', function(event) {
event.waitUntil(
clients.openWindow(urlOpen).then(function (){
event.notification.close();}));
});
这工作正常,但有时会出现在某些设备通知上。但是当点击通知时,它会在浏览器 url 栏中打开 null
。
我做错了什么?
最佳答案
您不能指望您的服务 worker 存在于 push
事件和 notificationclick
事件之间。浏览器很可能会在处理完 push
事件后关闭 worker,然后为 notificationclick
事件重新启动它,这意味着您的 urlOpen
变量已重新初始化为 null
。
我认为您可以以某种方式将 url 存储在通知对象本身上,这将是最好的 - 看起来有 an example of that here .否则你必须将它保存到 indexedDB 或类似的东西。
关于javascript - 无法在 'notificationclick' 事件中加载 Chrome 的 GCM 推送通知的数据 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32649765/