Navigator.serviceWorker.controller only works in webroot - service-worker

I am trying to get aServiceWorker to work from a subdirectory in webroot named appdashboard ... the serviceworker installs, runs and is visible from chrome://serviceworker-internals/, but its Navigator.serviceWorker.controller is null so I cannot communicate with it. If I don't restrict the scope (and move my serviceworker file to webroot) it works fine.
const serviceWorker = navigator
.serviceWorker
.register('appdashboard/dashboard_serviceworker.js', { scope: 'http://localhost/appdashboard/' })
.then((swReg) => {
console.log('[Service Worker (Dashboard)] service worker is registered', swReg);
swRegistration = swReg;
if (navigator.serviceWorker.controller != null) {
console.log("controller is working")
}
if (navigator.serviceWorker.controller == null) {
console.log("controller is NULL!") // <<<< its null :(
}
})
I simplified my serviceworker as much as possible to diagnose the issue, and controller is null even with this bare bones worker
self.addEventListener('message', function (event) {
console.log('got message')
});
self.addEventListener('activate', function (event) {
console.log('serviceworker activate')
event.waitUntil(self.clients.claim()); // Become available to all pages
});
self.addEventListener('install', function (event) {
console.log('install')
});
self.addEventListener('fetch', function (event) {
console.log('fetch')
});
self.addEventListener('push', (event) => {
console.log('received push')
});
self.addEventListener('notificationclick', function (event) {
console.log('registered notification click!')
});

I was using MVC routing so that my URL path was localhost/dashboard but my file structure was /appdashboard/, now I serve up an index.html from /appdashboard/ webroot and controller initializes.
This is the line that set me on the right path.
Remember the scope, when included, uses the page's location as its
base. Alternatively, if this code were included in a page at
example.com/product/description.html, the scope of './' would mean
that the service worker only applies to resources under
example.com/product.

Related

Second update service worker doesn't work

I hava a pwa with this sw.js:
const info = "versione: 1.0.0 data: 07-01-2020 12:46";
const CACHE = "pwa-offline";
const pages = [
// some files
];
self.addEventListener("install", function (event) {
//console.log("Install Event processing");
self.skipWaiting();
event.waitUntil(
caches.open(CACHE).then(function (cache) {
//console.log("Cached offline page during install");
return cache.addAll(pages);
})
);
});
self.addEventListener("activate", (event) => {
});
self.addEventListener("fetch", function (event) {
if (event.request.method !== "GET") return;
event.respondWith(
fetch(event.request)
.then(function (response) {
return fromCache(event.request);
})
.catch(function (error) {
//console.log("Network request Failed. Serving content from cache: " + error);
return fromCache(event.request);
})
);
});
async function fromCache(request) {
// Check to see if you have it in the cache
// Return response
// If not in the cache, then return error page
const cache = await caches.open(CACHE);
const matching = await cache.match(request);
if (!matching || matching.status === 404) {
return Promise.reject("no-match");
}
return matching;
}
async function updateCache(request, response) {
const cache = await caches.open(CACHE);
return cache.put(request, response);
}
and index.html with this code inside:
<script>
if ("serviceWorker" in navigator) {
navigator.serviceWorker
.register("./sw.js")//, {updateViaCache: 'none'})
.then(reg => {
//console.log("Registration successful", reg);
})
.catch(e =>
console.error("Error during service worker registration:", e)
);
} else {
console.warn("Service Worker is not supported");
}
</script>
I upload the pwa in a firebase site. When I change the sw.js (e.g. changing the date of versionDate, in this site https://developers.google.com/web/fundamentals/primers/service-workers/lifecycle I read: "Your service worker is considered updated if it's byte-different to the one the browser already has. (We're extending this to include imported scripts/modules too.)") and I upload, I see the new service worker is changed. But when I make a second change in sw.js and upload, the sw.js is not changed, so I can do only an update on sw.js and so to the whole site (because the sw.js caches all files of the site during the install process).
How can I update my site any time I want?
UPDATE: I watched that the problem is in android phone in desktop is ok.
UPDATE: Now also it works on android but the update is not immadiate. I see the update after some hours.
Your service worker caches all static files on your website. Consequently, you will need to edit your sw.js file whenever you are updating your website. One common way to do this is to attach a version number to your static cache name, for example pwa-offline-v1, then bump up the version number in the sw.js file whenever you are pushing an update to the site. This creates a new cache and stores the updated static files to it. You can then add an activate event listener on the service worker to delete the former cache using a function like this.
const info = "versione: 1.0.0 data: 07-01-2020 12:46";
const CACHE = "pwa-offline-v1";
const pages = [
// some files
];
self.addEventListener("install", function (event) {
//console.log("Install Event processing");
self.skipWaiting();
event.waitUntil(
caches.open(CACHE).then(function (cache) {
//console.log("Cached offline page during install");
return cache.addAll(pages);
})
);
});
self.addEventListener("activate", (event) => {
event.waitUntil(
Promise.all(
caches.keys().then((cacheNames) => {
cacheNames
.filter(cacheName => cacheName.startsWith('pwa-offline-') && cacheName !== CACHE)
.map(cacheName => caches.delete(cacheName))
})
)
);
});

Why are my service workers not working offline

Everything seems to be right and the files are being cached but it just doesn't work offline. Am I missing something obvious?
the cache.addAll did not want to work with my const FILES_TO_CACHE but do work when I put them in directly. Thus the repeated code.
Here is my service worker file:
const FILES_TO_CACHE = [
"/",
"/index.html",
"/style.css",
"/db.js",
"/index.js",
"/manifest.webmanifest"
];
const CACHE_NAME = "static-cache-v2";
const DATA_CACHE_NAME = "data-cache-v1";
// install
self.addEventListener("install", function(evt) {
evt.waitUntil(
caches.open(CACHE_NAME).then(cache => {
console.log("Your files were pre-cached successfully!");
return cache.addAll([
"/",
"/index.html",
"/style.css",
"/db.js",
"/index.js",
"/manifest.webmanifest"
]);
})
);
self.skipWaiting();
});
// activate
self.addEventListener("activate", function(evt) {
console.log("activated");
evt.waitUntil(
caches.keys().then(keyList => {
return Promise.all(
keyList.map(key => {
if (key !== CACHE_NAME && key !== DATA_CACHE_NAME) {
console.log("Removing old cache data", key);
return caches.delete(key);
}
})
).catch(err => console.log(err));
})
);
self.clients.claim();
});
// fetch
self.addEventListener("fetch", function(evt) {
console.log("fetched", evt.request.url);
if (evt.request.url.includes("/api/")) {
evt.respondWith(
caches
.open(FILES_TO_CACHE)
.then(cache => {
return fetch(evt.request)
.then(response => {
// If the response was good, clone it and store it in the cache.
if (response.status === 200) {
cache.put(evt.request.url, response.clone());
}
return response;
})
.catch(err => {
// Network request failed, try to get it from the cache.
return cache.match(evt.request);
});
})
.catch(err => console.log(err))
);
return;
}
});
link in html:
<script>
if ("serviceWorker" in navigator) {
navigator.serviceWorker.register("/service-worker.js").then(function() {
console.log("Service Worker Registered");
});
}
</script>
I also have my manifest linked in the HTML file.
Thank you in advance for any help you can provide!
If you look at the last line of code here:
// fetch
self.addEventListener("fetch", function(evt) {
console.log("fetched", evt.request.url);
if (evt.request.url.includes("/api/")) {
you see that there's a very simple mistake – your Service Worker is ONLY responding to requests that start with "/api/". If they don't, the SW doesn't touch them. Thus only "/api/" calls work offline (which doesn't make any sense :-), apis being mostly dynamic, right?).
(It is possible that there's another bug in the code of course, but this is a good point to start making changes.)

Why message listener does not work at first page load?

The problem that if I open an incognito window of chrome,
the updateLocalId() does not run. So I guess I dont receive events from sw.
But if I reload the page, everything works fine.
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/service-worker.js')
.then((registration) => {
console.info('[main] ServiceWorker registration successful: ', registration, ' ', '😍');
}, (err) => {
console.error('[main] ServiceWorker registration failed: 😠', err);
});
navigator.serviceWorker.addEventListener('message', async function (event) {
self.updateLocalId(event.data);
});
}
From SW I send message in the next way:
function send_message_to_all_clients(msg) {
self.clients.matchAll().then(clients => {
clients.map(client => client.postMessage(msg))
});
}
Found solution here
"A page is controlled by a service worker on navigation to an origin that the service worker is registered for. So the original page load that actually initializes the service worker is not itself controlled"
Updated function of sending message from SW:
function send_message_to_all_clients(msg) {
self.clients.matchAll({includeUncontrolled: true, type: 'window'}).then(clients => {
console.log('[sync] clients', clients);
clients.map(client => client.postMessage(msg))});
}

Workbox is not working and nothing show up in cache

I have added service worker and workbox as following
In template file:
<script type="text/javascript">
(function () {
if ('serviceWorker' in navigator) {
navigator.serviceWorker
.register('sw.js')
.then(function(registration) {
console.log('Service Worker registration successful with scope: ',
registration.scope);
})
.catch(function(err) {
console.log('Service Worker registration failed: ', err);
});
}
})();
</script>
And in sw.js, I have
importScripts('workbox-sw.prod.v2.1.2.js');
const workboxSW = new WorkboxSW();
if (workboxSW) {
console.log('Yay! workboxSW is loaded');
const staleWhileRevalidateStrategy = workboxSW.strategies.staleWhileRevalidate();
workboxSW.router.registerRoute('/*\.css/', staleWhileRevalidateStrategy);
} else {
console.log('Boo! workboxSW didn\'t load');
}
I can see in the console log that "Service Worker registration successful" and "Yay! workboxSW is loaded". But I don't see anything under cache storage (Application -> Cache Storage). How can I update it so that I can see cache content by the service worker?

Precedence rule for serviceworker in case of two serviceworkers

I am planning to have two service worker .But the Scope for one is subset of another's.
Ex: One is '/'
Other is '/images'
Now i am registering the two service workers from different places.
My doubt is when both serviceworkers are present and browser sends a request to /images , then which serviceworker will intercept it , as it is in scope of both the serviceworker.
Does the browser gives precedence to the more specialized scope ?
Edit: This my code for registering two Service Worker.Now i want to register both Service Workers when first call is made to '/'.
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register(serviceWorkerEndpoint1, { scope: serviceWorkerScope1 }).then(function (registration) {
Log.Log('ServiceWorker registration successful with scope: ' + registration.scope, "ServiceWorker1Installed", "ServiceWorkerInstalled");
}).catch(function (err) {
Log.Log('ServiceWorker registration failed: ' + err, "ServiceWorkerInstalled", "ServiceWorkerInstalled");
});
navigator.serviceWorker.register(serviceWorkerEndpoint2, { scope: serviceWorkerScope2 }).then(function (registration) {
Log.Log('ServiceWorker registration successful with scope: ' + registration.scope, "ServiceWorker2Installed", "ServiceWorkerInstalled");
}).catch(function (err) {
Log.Log('ServiceWorker registration failed: ' + err, "ServiceWorker2Installed", "ServiceWorkerInstalled");
});
}
Both work but only one is active per scope so the browser gives preference to the most specific one. I leave you a setup to verify (although I tried it by myself):
Folder structure:
.
├── images
│   └── sw-images.js
├── index.html
└── sw.js
In ./images/sw-images.js:
self.onfetch = event => {
if (event.request.url.indexOf('content') != -1)
event.respondWith(new Response('Hi from images'));
};
In ./sw.js:
self.onfetch = event => {
if (event.request.url.indexOf('content') != -1)
event.respondWith(new Response('Hi from root'));
};
In index.html:
<script>
Promise.all([
navigator.serviceWorker.register('sw.js', { scope: '/'}),
navigator.serviceWorker.register('images/sw-images.js', { scope: 'images/' })
])
.then(() => console.log('All right!'))
.catch(error => console.error(error));
</script>
./content.html
./images/content.html

Resources