I've been stuck on this problem for a while now. I have researched in depth and have spent a lot of time looking at similar questions on SO - but unsuccessful.
A bit of background. I have a website and an android app which effectively renders the website in a different form with different displays etc... The app knows to do this from incoming requests - as users have a particular string appended to the user agent (let's just say that string is 'MobileAppRequest'). Upon detecting this string in the user agent, the server knows to return a different html file. This allows the user to still go to the website on their browser and use the web version as well as have the app experience from their android app.
Now, upon using a service worker, it defaults to the user's standard user agent without including the appended string from the app. This then returns the web version within the app which messes it all up. I need to know how to set custom headers, or indeed, append a string to the user agent within the service worker. It says the headers are immutable when i try to directly change it but i know a way around this is to make a new request as a response.
Here is my SW.js
var CACHE_STATIC_NAME = 'static-v10';
var CACHE_DYNAMIC_NAME = 'dynamic-v2';
self.addEventListener('install', function (event) {
console.log('[Service Worker] Installing Service Worker ...', event);
event.waitUntil(
caches.open(CACHE_STATIC_NAME)
.then(function (cache) {
console.log('[Service Worker] Precaching App Shell');
cache.addAll([
'/',
'/static/media/next.png',
'/static/media/previous.png'
]);
})
)
});
self.addEventListener('activate', function (event) {
console.log('[Service Worker] Activating Service Worker ....', event);
event.waitUntil(
caches.keys()
.then(function (keyList) {
return Promise.all(keyList.map(function (key) {
if (key !== CACHE_STATIC_NAME && key !== CACHE_DYNAMIC_NAME) {
console.log('[Service Worker] Removing old cache.', key);
return caches.delete(key);
}
}));
})
);
return self.clients.claim();
});
self.addEventListener('fetch', function(event) {
event.respondWith(
fetch(event.request)
.then(function(res) {
return caches.open(CACHE_DYNAMIC_NAME)
.then(function(cache) {
cache.put(event.request.url, res.clone());
return res;
})
})
.catch(function(err) {
return caches.match(event.request);
})
);
});
I would appreciate the answers contain either the full sw.js or the whole function you're editing just so i don't make any mistakes integrating back into the code.