You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

VueJS中Service Worker缓存引发旧域名自动跳转失效及Cookie处理问题

解决方案

1. 入口HTML优先添加跳转逻辑

在旧域名的index.html最顶部(<head>标签起始位置)插入原生JS跳转代码,确保在Vue和Service Worker加载前执行,避免被缓存内容拦截:

<script>
// 检测当前是否为旧域名
if (window.location.hostname === 'lorem.ipsum.com') {
  // 清除旧域名关联的所有Cookie(若无需全清,可指定具体Cookie名称)
  document.cookie.split(";").forEach(function(c) {
    document.cookie = c.replace(/^ +/, "").replace(/=.*/, "=;expires=" + new Date().toUTCString() + ";path=/");
  });
  // 跳转至新域名,保留原路径与查询参数
  const newUrl = new URL(window.location.href);
  newUrl.hostname = 'dolor.ipsum.com';
  window.location.replace(newUrl.toString());
}
</script>

2. 修改Service Worker强制清缓存并跳转

更新旧域名的Service Worker代码,在激活阶段清除所有缓存,并主动通知客户端跳转:

workbox.core.setCacheNameDetails({ prefix: 'd4' });

const LATEST_VERSION = process.env.VUE_APP_VERSION;
const NEW_DOMAIN = 'dolor.ipsum.com';

self.addEventListener('activate', async () => {
  // 清除旧域名下所有缓存
  if (caches) {
    const cacheKeys = await caches.keys();
    await Promise.all(
      cacheKeys.map(key => caches.delete(key))
    );
    console.log('%c 已清除旧域名所有缓存', 'background: #333; color: #ff0000');
  }

  // 通知所有打开的旧域名客户端跳转
  const clients = await self.clients.matchAll({ type: 'window' });
  clients.forEach(client => {
    if (client.url.includes('lorem.ipsum.com')) {
      const newUrl = new URL(client.url);
      newUrl.hostname = NEW_DOMAIN;
      client.navigate(newUrl.toString());
    }
  });

  self.skipWaiting();
});

self.addEventListener('fetch', event => {
  // 拦截所有旧域名请求,直接重定向到新域名
  if (event.request.url.includes('lorem.ipsum.com')) {
    const newUrl = new URL(event.request.url);
    newUrl.hostname = NEW_DOMAIN;
    event.respondWith(Response.redirect(newUrl.toString(), 301));
  }
});

workbox.skipWaiting();
workbox.clientsClaim();

self.__precacheManifest = [].concat(self.__precacheManifest || []);
workbox.precaching.suppressWarnings();
workbox.precaching.precacheAndRoute(self.__precacheManifest, {});

3. 前端注册Service Worker时增加域名检测

修改Vue项目中注册Service Worker的代码,初始化时优先检测旧域名并跳转:

import { register } from "register-service-worker";

// 优先检测旧域名,直接跳转
if (window.location.hostname === 'lorem.ipsum.com') {
  const newUrl = new URL(window.location.href);
  newUrl.hostname = 'dolor.ipsum.com';
  window.location.replace(newUrl.toString());
} else if (process.env.NODE_ENV === "production") {
  register(`${process.env.BASE_URL}service-worker.js`, {
    ready() {
      console.log("App is being served from cache by a service worker.\n");
    },
    registered() {
      console.log("Service worker has been registered.");
    },
    cached() {
      console.log("Content has been cached for offline use.");
    },
    updatefound() {
      console.log("New content is downloading.");
    },
    updated() {
      console.log("New content is available; please refresh.");
      setTimeout(() => {
        window.location.reload();
      }, 1000)
    },
    offline() {
      console.log("No internet connection found. App is running in offline mode.");
    },
    error(error) {
      console.error("Error during service worker registration:", error);
    },
  });
}

关键说明

  • 入口HTML跳转:这是最直接的触发点,无论浏览器是否缓存了旧页面,只要加载index.html就会执行跳转逻辑。
  • Service Worker拦截:确保所有旧域名的请求(包括静态资源)都被重定向到新域名,同时清除旧缓存避免残留影响。
  • Cookie处理:清除旧域名Cookie可避免绑定的缓存状态或登录信息干扰跳转,可根据实际需求调整清除范围。
  • 301重定向:告知浏览器永久转向新域名,减少后续不必要的旧域名请求。

内容的提问来源于stack exchange,提问作者Maikon Cg

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 13:37:23