简体   繁体   中英

How to redirect a PWA to a new server

I have an app that registers service worker to make the app available offline. Now I need to move the app to a new server, so I set up a 301 redirect for the root page. But existing caches seem to ignore this and always serve the old app on the old URL. How do I force them to update?

Another simple way to do that is by using workbox-window. you can detect new service workers installation and prompt user to reload the page or reload it without user permission. for more detail please read this .

I hope this can help you.

Found this: https://github.com/NekR/self-destroying-sw

After refreshing and re-opening the page, it finally picked up the redirect.

You can update service worker code with:

ServiceWorkerRegistration.update();

Here there are a example: example

Note: The update code run when there are diffs with the serviceworker intalled in the browser, in this instance de new service worker run the updates but the new code don't are avalible until the website close and open again.

Thankfully this done automatically once you close the browser.

Otherwise you would have to add an update for your PWA app. The update would have to consist of a new SW (as per usual PWA update). And in any script just execute JS redirect with location.href .

Don't seem like you can do it via HTTP redirects.

If you don't want to wait forever for someone to clear cache or kill their service worker you can detect a redirect.

I've described details here: https://enux.pl/article/en/2022-05-26/pwa-detecting-redirects-service-workers

In short: It is not possible to get a URL of a redirect. Heck you will not even get a status number if the new URL would brake CORS. So what you have to do is use a redirect option:

var urlForTestingRedirs = '/something/local.css';
fetch(urlForTestingRedirs, {
    // this is crucial
    redirect: 'manual',
    // use head to be lite
    method: 'HEAD',
    // make sure HTTP cache is skipped
    cache: 'no-cache',
}).then(function(response) {
    if (response.type == 'opaqueredirect') {
        clearAllForPwa()
    }   
});

You can just do it in a standard script tag. So no need to do this fetch in your sw.js or anything like that.

Note that clearAllForPwa function will heavily depend on what caches are you using. So what Web Storage API do you use (if any) or maybe you use IndexDB with eg localforage... Whatever is the case it is nice to clean up after yourself 😉

Again, see more information in the article I mentioned above.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM