Search code examples
javascriptangularjspush-notificationweb-worker

How to change scope variable when push notification received


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.


Solution

  • 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