'update PWA react app (using CRA) with user clicked button through service worker
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?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
