Tell HN: Service Workers === Browser Background Tasks
The term "service worker" has confused me for a while, now I see it to be bad jargon selection. You can use "service workers" to send push notifications, load things from cache, and allow for offline behavior of your application (turn off your wifi and load twitter, for example). I think the term "browser background task" is more apt, I am sad another much more confusing and less relevant term was chosen years ago.
19 comments
[ 3.3 ms ] story [ 56.9 ms ] threadInteresting read: https://man7.org/linux/man-pages/man7/daemon.7.html
1. Service worker lifetime is not tied to a particular window. They can live across multiple windows either at the same time or across time. (Think of a tab closed then later reopened.) A background function will stop running when the tab is closed.
2. Service workers have some ability to intercept network requests. In a page you could patch APIs like fetch and XMLHttpRequest but you have no ability to intercept image loads or top-level navigations.
3. Other APIs such as receiving push notifications are also tied to service workers (likely because of the lifetime restrictions, otherwise the browser would need to decide which tab to deliver a notification to or open a new one if none are open).
To illustrate, assume I frequently browse a blog and want to trick my browser into thinking that I have "favorited" every post. It's trivial to write a for loop that iterates over response.json and sets `is_favorite = true`. But it's not as clear to me where this script should ideally live in order to have the logic always executed before the response is made available to the site.
Your comment made me think about whether I can replace my overkill solution (https://requestly.io/) with something lightweight.
Your bet is to use a browser extension to override the response of that specific API and sort of change the response.
PS - Why do you think this is an overkill solution?
Only because my use case is very trivial and does not require most of the features. On the other hand, it did get the job done on the first try so I can't really complain.
Yes but in this case you would need to setup a reverse proxy so your service worker and the intercepted page runs in the same domain. You could use cors-anywhere[1] for that.
[1] https://cors-anywhere.herokuapp.com/
Service workers are threads. They’re basically separate JavaScript processes you communicate with with IPC, with other special privileges and capabilities allotted to them.