3

While working on GCM push notification for Chrome, I have set up push notifications for when a service worker receives a push event for GCM.

I am launching a service call. That service returns a data object in which I have a URL which I want to open at the time when the user clicks on the notification

Here is the code I have so far.

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();}));

});

This is working fine but sometime on some device notifications. But when clicking on notifications, it's opening null in the browser url bar.

What am I doing wrong?

4

1 回答 1

4

你不能指望你的服务工作者存在于push事件和notificationclick事件之间。浏览器很可能会在处理完事件后关闭 worker push,然后为notificationclick事件重新启动它,这意味着您的urlOpen变量已重新初始化为null.

我认为您可能可以以某种方式将 url 存储在通知对象本身上,这将是最好的 - 看起来这里有一个示例。否则,您必须将其保存到 indexedDB 或类似的东西。

于 2015-09-18T13:37:24.177 回答