3
votes

I have a notification icon in my web app that shows the number of notifications. The front end of the application is made using angularjs.

The count for the icon is stored in a $rootScope variable. I want to increment the variable(or call a web service that returns count) when a push notification is received.

The serviceworker.js file does not have access to the scope variables in angularjs. How do I change the count variable's value from the serviceworker.

I thought of adding a change event listener on localStorage item.

On logging in, I will create a item.

localStorage.setItem('notifCount', 0);

When I receive a push notification, I will increment notifCount in localStorage in serviceworker.js and the change event will fire. I could add the localStorage change listener in one of controller files and call a web service or just increment the $rootScope variable.

But this would happen even when someone manually changes the localStorage in dev tools.

I want to know if I can do it this way(if it's the right way) or is there a better method. I don't feel like this is the right way.

1
Assuming you have the communication between Angular (client) and service worker, you should wrap the updating of the angular variable in $apply. If you haven't gotten communication working, take a look at a number of service worker communication links from google (craig-russell.co.uk/2016/01/29/…). - kendavidson
using locationStorage for this seems weird. You can e.g. register service worker listener in app.run and change $rootScope variable there. - Petr Averyanov
@PetrAveryanov and you can't access the localStorage in serviceworker - Dwigh

1 Answers

0
votes

Data is sent between workers and the main thread via a system of messages — both sides send their messages using the postMessage() method, and respond to messages via the onmessage event handler (the message is contained within the Message event's data attribute.) The data is copied rather than shared.

For more information, see