Saturday, December 3, 2016

Storage in ServiceWroker while site is not running


Few days back while working with service workers I got caught with a unique kind of problem. I wanted to show notification data to the users in a dropdown and the tricky part was the notifications sent  while site was not open in any tab. I was not able to store that information as service worker cant directly use DOM. As site was not open in any tab, it couldn't post it to the site JS which could have inserted it to localstorage.

Fortunately, I was able to solve the problem. As a workaround I tried a very tricky implementation. It was based on the fact that ServiceWorker specifications said it can not access DOM and it cannot store values in browser storage but it did not said anything about the global variables. So, I stored the values in global Variable just by declaring an array outside of all the methods.

var notificationList = new Array();

Parsed information of notification is then pushed to this list from the Event Listner where serviceworker is listening to push event.

notificationList.unshift(parsedNotificationData); 

Now this notification information is available and stored inside the serviceworker which webpage JS can ask for on load.

Hope this was a bit helpful.