Skip to content

Fix broken ServiceWorker

Jano requested to merge fix_service_worker into master

What does this MR do?

This MR fixes a regression from !1442 (merged) which literally completely broke push notifications.

I don't know how I could not notice this, maybe the service worker did not update in my test environment.

The reason for the service worker breaking is that I imported the code used to post push subscriptions to the server. This code relied on the window object (for fetch etc.). In the service worker, there is no 'window' object available. However, all non-DOM-specific parts of window are implemented by the ServiceWorkerGlobalScope.

https://developer.mozilla.org/en-US/docs/Web/API/WorkerGlobalScope

'self' always returns the current global scope – for JavaScript in the browser window, that's 'window', for JavaScript in a ServiceWorker, it's the ServiceWorkerGlobalScope. That's why I replaced 'window' with 'self' in all parts of the code that are used in the service worker.

How confident are you it won't break things if deployed?

Quite. I touched a part of the code that most frontend code relies on (base.js), but I tested many pages that rely on the fetch functionality, and they work as expected, which should always be the case, as 'self' is being resolved to the the normal, original 'window' object when the code runs in the window.

Links to related issues

I added the Exception shown in the browser console that is caused by this to #831 (closed).

How to test

  1. Checkout branch locally
  2. Open developer console on localhost:18080
  3. See a TypeError from the ServiceWorker (e. g. TypeError: ServiceWorker script at foo for scope bar threw an exception during script evaluation.) if you are on master, don't see it if you are on branch fix_service_worker.

Checklist

  • added a test, or explain why one is not needed/possible...
  • no unrelated changes
  • asked someone for a code review
  • joined #foodsharing-beta channel at https://slackin.yunity.org
  • added an entry to CHANGELOG.md (description, merge request link, username(s))
  • Once your MR has been merged, you are responsible to update the #foodsharing-beta Slack channel about what has been changed here. They will test your work in different browsers, roles or other settings
Edited by Alex

Merge request reports