I want to update PWA application when new content is available. Since we can't access DOM from service worker, how can I exactly do that? The service worker correctly recognize the new content, but I can't bind a hook or context to show my modal or update button in react. Any help?
service worker register and onUpdate function:
function RegisterValidSW(swUrl, config) {
navigator.serviceWorker
.register(swUrl)
.then((registration) => {
registration.onupdatefound = () => {
const installingWorker = registration.installing;
if (installingWorker == null) {
return;
}
installingWorker.onstatechange = () => {
if (installingWorker.state === 'installed') {
if (navigator.serviceWorker.controller) {
// At this point, the updated precached content has been fetched,
// but the previous service worker will still serve the older
// content until all client tabs are closed.
// setUpdate(true);
// registration.waiting.postMessage({ type: 'SKIP_WAITING' });
console.log(
'New content is available and will be used when all ' +
'tabs for this page are closed. See https://cra.link/PWA.'
);
// Execute callback
if (config && config.onUpdate) {
config.onUpdate(registration);
}
} else {
// At this point, everything has been precached.
// It's the perfect time to display a
// "Content is cached for offline use." message.
console.log('Content is cached for offline use.');
// Execute callback
if (config && config.onSuccess) {
config.onSuccess(registration);
}
}
}
};
};
})
.catch((error) => {
console.error('Error during service worker registration:', error);
});
}
this function is in the serviceWorkerRegistration.js file. We can add registration.waiting.postMessage({ type: 'SKIP_WAITING' }); function to call skipWaiting but it doesn't wait for user interaction and can't reload the page. how can I solve that?
You can try passing in an onUpdate function when you register the service worker. In that function send a SKIP_WAITING message to the service worker followed a page reload.
Your server worker should have SKIP_WAITING message hander. Something like this:
This is working for me.
What I am still struggling with is how to get the app updated if the user leaves the app open. As in,
and just leaves it open forever and ever...
This should probably go in a new question, but I thought it might be relevant to your use case.