Search code examples
javascripthtmlprogressive-web-appsservice-worker

How to determine, in a service worker, which HTML5 page orginated the fetch request?


Is there a mechanism in a service worker, which I am unaware, which can allow me to know from which page a fetch request is fired from?

Example: I have an HTML page uploaded to my website at /aPageUploadedByUser/onMySite/index.html, I do want to make sure none of the authorization headers gets passed to any fetch request made by /aPageUploadedByUser/onMySite/index.html to any source.

If my service worker does somehow know the originating page of this request, I can modulate them for safety.


Solution

  • To answer your question (but with a caveat that this is not a good idea!), there are two general approaches, each with their own drawbacks:

    • The Referer: request header is traditionally set to the URL of the web page that made a request. However, this header may not always be set for all types of requests.

    • A FetchEvent has a clientId property, and that value can be passed to clients.get() to obtain a reference to the Client that created the request. The Client, in turn, has a url property. The caveats here are that clients.get() is asynchronous (meaning you can't use its result to determine whether or not to call event.respondWith()), and that the URL of the Client may have changed in the interval between the request being made and when you read the url property.

    With those approaches outlined, the bigger problem is that using a service worker in this way is not a safe practice. The first time a user visits your origin, they won't have a service worker installed. And then on follow-up visits, if a user "hard" reloads the page with the shift key, the page won't be controlled by a service worker either. You can't rely on a service worker's fetch event handler to implement any sort of critical validation.