从 React 切换到 Next.js 后,由于 Service Worker 的缓存,网站没有刷新.如何强制更新? [英] A website is not refreshing because of caching of service worker, after switching from React to Next.js. How to force update?

查看:63
本文介绍了从 React 切换到 Next.js 后,由于 Service Worker 的缓存,网站没有刷新.如何强制更新?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一个基于 react 的网站有一个用于缓存的 service worker.我们使用 unregister() 代码运行网站,并将网站移植到 Next.js .尽管在某些机器上,注销代码从未运行过,所以现在这些机器正在运行旧的 React 代码,并且没有反映所做的任何更改并推送到服务器.更改正在隐身和其他运行注销代码的机器上运行.它在 Caddy 服务器上.

A website made on react had a service worker for caching. We ran the website with unregister() code and the website was ported to Next.js . Although on some machines, the unregister code never ran, so now those machines are running the old react code and not reflecting any changes made and pushed to the server. The changes are running on incognito and other machines where the unregister code ran. It is on Caddy server.

如何强制它从服务器端刷新?我们可以在我们的机器上清除缓存或取消注册 Service Worker,但我们不知道有多少客户端拥有旧代码.

How can I force it to refresh from server side? We can clear cache or unregister the service worker on our machine but we don't know how many clients have the old code.

谢谢!

推荐答案

那么问题就解决了.制作了一个新的 Service Worker 文件,仅包含删除 Service Worker 的代码.

So the issue has been solved. Made a new service worker file, with just the code to remove the service worker.

if ("serviceWorker" in navigator) {
  window.addEventListener("load", function () {
    navigator.serviceWorker.getRegistrations().then((registrations) 
=> {
      for (let registration of registrations) {
       registration.unregister().then((bool) => {
          console.log("unregister: ", bool);
        });
     }
    });
  });
}

并将此文件放在保存前一个 service worker 的确切位置(您可以从 chrome 开发人员工具中找到).还包括在 index.html 或 _document.js(对于 next.js)中链接此文件的脚本标记.这应该可以解决问题.

And put this file in the exact location where the previous service worker was kept (You can find this out from the chrome developer tools). Also include the script tag linking this file in index.html or _document.js (for next.js). This should resolve the issue.

这篇关于从 React 切换到 Next.js 后,由于 Service Worker 的缓存,网站没有刷新.如何强制更新?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆