Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to load Javascript file in a Service Worker dynamically?

I can't use any solutions that involve creating a <script> tag dynamically because document does not exist in a ServiceWorker context.

In this case I want to load analytics toolkit so I can track when SW-triggered Notifications are interacted with by the user.

Any ideas?

like image 773
hexsprite Avatar asked Mar 27 '16 19:03

hexsprite


1 Answers

That sounds like the intended use case of the importScripts() method.

The imported script shares the global scope with your service worker, so modifying self via, e.g., self.addEventListener() or self.someIdentifier = 'blah' will have the same effect as it would from within the main service worker script.

like image 102
Jeff Posnick Avatar answered Sep 28 '22 10:09

Jeff Posnick