Pushpad
Articles › Troubleshooting, Web Push Notifications

Update the service worker and the scripts imported with importScripts

  • # service-worker

If you change the Javascript code of a service worker, the browser may not  apply the update immediately (as we have already discussed).

In order for the update to take effect you need to:

  1. Change some code inside the main service worker (if you only change code inside a script imported with importScripts the browser will not detect the change)
  2. Visit a page of the website (that activates the service worker or calls serviceWorker.register) - sometimes you also need to refresh that page
  3. Now the new service worker is installed, but it can't be activated until you terminate the previous service worker: close and reopen the browser

If a user doesn't visit your website, but the service worker is activated by the push messages, the browser will try to fetch a new version of the service worker automatically after 24 hours (this behavior is described by Google, but probably is not implemented in all browsers yet).

Note that scripts imported with importScripts are cached by the browser and even if you have updated the main service worker they may not get updated. In order to force the update of the imported scripts add a query string to the imported script path.

For example, if you have the following line inside your service worker:

importScripts('https://pushpad.xyz/service-worker.js');

You can force the update of the service worker and its dependency by adding an arbitrary query string (e.g. v2, v3, v4... the current timestamp, or anything else - the query string ?foobar would have the same effect):

importScripts('https://pushpad.xyz/service-worker.js?20170501');

If you want to make sure that the the service worker code that runs in your browser is updated you can use the browser developer tools.

Note that this behavior will be fixed in the future versions of the browsers and you can expect easier updates. However, on April 2017, you still need to use this hack.