Reputation: 397
I am using service worker to implement web push notifications. Whenever I change some code of service-worker, that change is not reflected in service-worker on browser unless I delete cookie/cache. Is this normal behaviour or I have to add some function to update service-worker?
Upvotes: 3
Views: 1353
Reputation: 9821
Service worker files are cached for a Max of 24 hours if the cache header is sent with the service worker file.
First step is to set the cache headers to 0 to not cache.
When a browser finds a new service worker it will download and install it. It won't take affect until all pages that are currently controlled by the service worker are closed. For a normal user this isn't a problem. During development in chrome you can use Ctrl+ shift + R to do a hard refresh which forces a page not to be controlled by service worker, allowing your be service worker take control on the next refresh.
Final option is to use skip waiting in install step and claim in the activate step to force a new service worker to instantly activate and control any pages. If earn against this as it's easy to get into weird scenarios.
Update: Browsers are changing this default behavior - Firefox will now ignore the cache header and other browsers are likely to implement the same behaviour
Upvotes: 5
Reputation: 6847
To answer your specific question: yes, the behaviour is intentional and yes, yo can call an update function. Use update()
method on the service worker registration. From MDN:
The update method of the ServiceWorkerRegistration interface attempts to update the service worker. It fetches the worker's script URL, and if the new worker is not byte-by-byte identical to the current worker, it installs the new worker. The fetch of the worker bypasses any browser caches if the previous fetch occurred over 24 hours ago.
Notice it says the SW fetch will bypass any browser cache if the previous fetch is older than 24h so you should disable caches while developing service workers.
Upvotes: 0