I have created a very simple service worker as you see below. It simply intercepts the fetch requests and adds X-Custom-Header
to the headers.
self.addEventListener('install', () => {
self.skipWaiting();
});
self.addEventListener('activate', event => {
event.waitUntil(self.clients.claim());
});
self.addEventListener('fetch', event => {
event.respondWith(fetchWithAuthorizationHeader(event.request));
});
function fetchWithAuthorizationHeader(request) {
const newHeaders = new Headers();
newHeaders.set('X-Custom-Header', `123`);
return fetch(request, { headers: newHeaders });
}
I register the service worker for http://localhost:3000 like this:
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/sw.js', {
scope: '/',
});
}
In chrome and firefox, when I navigate to http://localhost:3000 (service worker is already installed), only one request is recevied by the back-end. But when I do the same in Safari, two requests are received by the back-end.
I investigated a bit and realised that in Safari, when I type http://localhost:3000 in the browser address bar, a request is sent before the service worker starts, then after the service worker starts, another request is sent which gets intercepted by the service worker.
I don’t understand why Safari has this strange behaviour. Does anybody have an idea how to prevent this?
P.S: I tried with different versions of safari both on mac and iphone. Got the same results everytime.