Sunday, 3 November 2019

Service Worker: Append header to requests for CSS & JS files

I've been trying to use service workers for (what seems like hours & hours), to attach a simple header to all requests. Whats frustrating is, it sort of works.

Attempt 1:

self.addEventListener("fetch", event => {
   const modifiedHeaders = new Headers({
      ...event.request.headers,
      'API-Key': '000000000000000000001'
   });
   const modifiedRequest = new Request(event.request, {
      headers: modifiedHeaders,
   }); 
   event.respondWith((async () => {
     return fetch(modifiedRequest);
   })());
});

The above code works for HTML files however for CSS & JS files I get the follow error

ReferenceError: headers is not defined

If I disable the header requirement the page loads with images and javascript and I can interact with it like normal.

Attempt 2:

var req = new Request(event.request.url, {
   headers: {
     ...event.request.headers,
      'API-Key': '000000000000000000001'
      },
   method: event.request.method,
   mode:  event.request.mode,
   credentials: event.request.credentials,
   redirect: event.request.redirect,
   referrer: event.request.referrer,
   referrerPolicy: event.request.referrerPolicy,
   bodyUsed: event.request.bodyUsed,
   cache: event.request.cache,
   destination: event.request.destination,
   integrity: event.request.integrity,
   isHistoryNavigation: event.request.isHistoryNavigation,
   keepalive:  event.request.keepalive
 });

This attempt, I simply built a new request, which successfully included the new header on CSS & JS file requests. However, When I do a POST or redirect, things stop working and behave strange.

What is the correct approach for this? I feel that attempt 1 is the better path, but I can't seem to create the Headers object on the request no matter what I do.

The version of chrome I am using is

Version 78.0.3904.70 (Official Build) (64-bit)

The site is an internal developer tool so cross browser compatibility isn't required. So I'm happy to load any additional libs / enable experimental features etc.



from Service Worker: Append header to requests for CSS & JS files

No comments:

Post a Comment