Mossroy
Mossroy

Reputation: 770

How to make browsers pass all HTTP headers to a ServiceWorker?

I need in a ServiceWorker to read the HTTP headers sent in the browser request.

My problem is that the event.request object only has a few HTTP headers (accept, accept-language or user-agent), not all of them.

Here is a test-case with a simple HTML page that runs a ServiceWorker :

<html>
    <head>
        <script type="text/javascript">
            navigator.serviceWorker.register('./service-worker.js');
        </script>
    </head>
    <body>
        <img src="Note.png"/>
    </body>
</html>

This ServiceWorker simply dumps the request headers it gets :

self.addEventListener('fetch', function(event) {
    for (let key of event.request.headers.keys()) {
        console.log("key=" + key + " value=" + event.request.headers.get(key));
    }
});

This is the result on Firefox :

key=accept value=*/*
key=accept-language value=fr-FR,fr;q=0.8,en-US;q=0.5,en;q=0.3

And the result on Chromium :

key=accept value=image/webp,image/apng,image/*,*/*;q=0.8
key=user-agent value=Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/68.0.3440.75 Chrome/68.0.3440.75 Safari/537.36

Where I would expect to have all the headers that are sent to the server if I remove the ServiceWorker :

Accept: image/webp,image/apng,image/*,*/*;q=0.8
Accept-Encoding: gzip, deflate, br
Accept-Language: fr-FR,fr;q=0.9,en-US;q=0.8,en;q=0.7
Connection: keep-alive
Host: localhost:8383
Referer: http://localhost:8383/testcase-serviceworker-fetch-request-headers/index.html
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/68.0.3440.75 Chrome/68.0.3440.75 Safari/537.36

How could I read these HTTP headers that are missing in event.request.headers?

Upvotes: 0

Views: 542

Answers (1)

Mossroy
Mossroy

Reputation: 770

Based on the comments from https://github.com/w3c/ServiceWorker/issues/212, I suppose it's not possible.

My understanding is that the browser adds these headers later in the process of the request, so they're not yet available to a ServiceWorker.

Upvotes: 1

Related Questions