无法在“notificationclick”事件中加载GCM推送通知的Chrome数据URL

3
在处理Chrome的GCM推送通知时,当服务工作者接收到GCM的推送事件时,我已经设置了推送通知。
我正在启动一个服务调用。该服务返回一个数据对象,在该对象中我有一个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();}));

});

这段代码在大部分设备上能够正常工作,但有时候会出现通知问题。当点击通知时,浏览器的地址栏中显示 null

我做错了什么?

1个回答

4
您不能指望在push事件和notificationclick事件之间存在您的服务工作者。浏览器很可能会在处理完push事件后关闭该工作者,然后在notificationclick事件中重新启动它,这意味着您的urlOpen变量已被重新初始化为null
我认为您可以在通知对象本身上以某种方式存储url,这将是最好的方式 - 看起来这里有一个示例。否则,您将不得不将其保存到indexedDB或类似的东西中。

谢谢你,Brendan!!我已经将URL存储在notification.data中,现在它运行良好。 - Yogendra
你好, 示例的URL无法使用。不过我已经尝试了你的建议。我会分享结果。 - egemen
看起来现在已经在这里了:https://github.com/gauntface/simple-push-demo/blob/master/src/service-worker.js - Brendan Ritchie

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接