最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to redirect a PWA to a new server - Stack Overflow

programmeradmin1浏览0评论

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?

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?

Share Improve this question asked Aug 2, 2019 at 15:52 rivriv 7,3633 gold badges41 silver badges74 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 1

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./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.

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 e.g. localforage... Whatever is the case it is nice to clean up after yourself

发布评论

评论列表(0)

  1. 暂无评论