I am a bit of a PWA novice – and I’m trying to use messaging from the front-end to a service-worker.js to trigger the download of images one by one on a page. This causes those images to be auto-cached through my fetch event. To track things – I have a simple dial on each page to indicate how many images are cached.
The code is all working ok and will do as requested if I sit and watch, BUT if I navigate to a new page whilst the download is still running then the download seems to stop (and I see no further console messages being added, no dev-tools debug breakpoints hitting, and no further progress showing on the dial when I return to the original page).
What am I doing wrong here? [My premise here is that [I believe] service-worker processing should continue running regardless of page navigations]
service-worker.js:
self.addEventListener('message', event => {
if ( event.data && typeof(event.data)=='string' ) {
let firstPart, secondPart;
if (event.data.indexOf(':') > 1) {
let parts = event.data.split(':');
firstPart = parts.shift();
secondPart = parts.join(':');
}
else {
firstPart = event.data;
secondPart = '';
}
if (firstPart === 'download-images') {
let parts = secondPart.split(':');
let id = parts.shift();
secondPart = parts.join(':');
let images= secondPart.split(',');
doImagesDownloadLoop(images, id)
.then(() => {
doPostMessage('showmsg:Pages download complete');
})
.catch(error => {
doPostMessage(`showmsg:Failed to download or filter images: ${error}`);
});
}
}
});
async function doImagesDownloadLoop(images, id) {
for (let i = 0; i < images.length; i++) {
try {
await downloadImage(images[i], i, images.length, id);
let percentageLoaded = ((i + 1) / images.length) * 100;
doPostMessage(`update-dial:${id}:${percentageLoaded}`);
} catch (error) {
doPostMessage(`showmsg:Failed to download or filter image ${i + 1}/${images.length}: ${error}`);
}
}
}