Yogendra Yogendra - 1 month ago 13
Javascript Question

Not able to load data URL for GCM push notification for chrome in 'notificationclick' event

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?

Answer

You can't count on your service worker existing between the push event and the notificationclick event. The browser may very well shut down the worker after the push event has been handled, and then restart it for the notificationclick event, meaning that your urlOpen variable has been reinitialized to null.

I think you can probably store the url on the notification object itself somehow, which would be nicest - looks like there is an example of that here. Otherwise you would have to save it to indexedDB or something like that.

Comments