Update firebase messaging service worker when there is change in firebase config

Viewed 1008

I am using firebase for receiving push notifications in a react project.

Is there any way I can maintain the multiple versions of firebase-messaging-sw.js or just update the browser service worker from React (javascript) code?

Everything seems working fine. What I actually need is when I make changes in the firebase-messaging-sw.js, the service worker must be updated in the frontend user's browser.

Any help on this would be highly appreciated. Thank you.

1 Answers

So the issue is that you need to destroy/unregister the old service worker before you can register a new one (or force update with a newer version). You can do this manually in your local chrome browser by going into the inspection mode, selecting the service worker tab and click "update on reload". However this will not be a good solutin for any production applciation. A better, programmatic way is outlined in this medium post which you might find helpful: https://medium.com/@nekrtemplar/self-destroying-serviceworker-73d62921d717 Basically you can create a self-cleaning service worker routine with something along the lines of

navigator.serviceWorker.getRegistrations().then( function(registrations) { for(let registration of registrations) { registration.unregister() .then(function() { return self.clients.matchAll(); }) .then(function(clients) { clients.forEach(client => { if (client.url && "navigate" in client){ client.navigate(client.url)); } }); } });

which removes the old serrvice worker and than could use an activate event to trigger an update to the different clients. This github repo has more details on the idea: https://github.com/NekR/self-destroying-sw.

Update: I just found this blog post which might give you an even more elegant solution. https://betterprogramming.pub/let-users-know-when-you-have-updated-your-service-worker-in-create-react-app-b0c2701995b3

Related