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

使用Workbox构建PWA在Safari中出现'Response served by service worker has redirections'错误

解决Safari中Workbox PWA的“Response served by service worker has redirections”错误

问题背景

使用Workbox构建PWA时,仅在Safari浏览器中触发以下错误:

Response served by service worker has redirections

该问题出现在OAuth登录后访问/auth/login或/receipt路由时。当前采用App Shell模式,所有导航请求返回缓存的/index.html,此配置在Chrome中运行正常,但Safari无法正常工作。

当前Workbox配置:

registerRoute(({ request, url }) => {
  if (request.mode !== 'navigate') return false;
  if (url.pathname.startsWith('/_')) return false;
  if (url.pathname.match(/\/[^/?]+\.[^/]+$/)) return false;
  return true;
}, createHandlerBoundToURL('/index.html'));

原因分析

Safari对Service Worker处理导航请求的重定向逻辑校验更严格:OAuth登录后服务器通常会返回3xx重定向响应,此时如果Service Worker直接返回缓存的/index.html,Safari会判定这是非法的重定向拦截,从而抛出错误。Chrome则允许这种处理方式。

解决方案

1. 排除OAuth相关路由,让其走网络请求

修改Workbox路由匹配规则,将/auth开头的路由排除在App Shell缓存逻辑之外——这类路由需要服务器处理重定向或认证流程,不能直接返回缓存页面:

registerRoute(({ request, url }) => {
  if (request.mode !== 'navigate') return false;
  if (url.pathname.startsWith('/_')) return false;
  if (url.pathname.startsWith('/auth')) return false; // 排除OAuth登录相关路由
  if (url.pathname.match(/\/[^/?]+\.[^/]+$/)) return false;
  return true;
}, createHandlerBoundToURL('/index.html'));

2. 处理/receipt路由的两种情况

  • 如果/receipt是前端路由:配置服务器,让该路径直接返回200状态的/index.html,避免服务器返回重定向。这样Service Worker返回缓存页面时,Safari不会判定为异常。
  • 如果/receipt需要服务器处理逻辑:同样将其加入排除列表,让请求走网络流程:
    // 在匹配条件中添加
    if (url.pathname.startsWith('/receipt')) return false;
    

3. 验证缓存的index.html状态

在Safari开发者工具的「存储」→「缓存存储」中,确认/index.html的响应状态为200,不存在重定向(3xx)记录。如果缓存的响应是重定向状态,需清除缓存并重新注册Service Worker。

内容的提问来源于stack exchange,提问作者Jacob Goh

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.12 12:42:36