Electron应用调用window.loadURL时触发非ISO-8859-1字符请求错误
window.loadURL 触发 PrecacheCacheKeyPlugin 编码错误 问题现象
运行 Electron.js 应用并执行 window.loadURL('https://example.test') 时,控制台抛出如下错误:
Uncaught (in promise)
TypeError: Failed to construct 'Request': Failed to read the
'headers' property from 'RequestInit': String contains non
ISO-8859-1 code point.
at K.cacheKeyWillBeUsed (PrecacheCacheKeyPlugin.js:24:19)
at a (StrategyHandler.js:422:40)
at H.getCacheKey (StrategyHandler.js:355:52)
at H.cacheMatch (StrategyHandler.js:225:45)
at $._handle (PrecacheStrategy.js:64:40)
at $._getResponse (Strategy.js:144:35)
重新加载页面(Command + R)后应用恢复正常,直接在浏览器中打开该 URL 也无异常。调试 headers 相关内容时,显示状态正常:
可能的解决方案
1. 修正 Service Worker 的缓存键生成逻辑
错误根源是 Precache 插件处理请求头时遇到了非 ISO-8859-1 编码字符,可通过自定义 cacheKeyWillBeUsed 回调规范化请求头:
workbox.precaching.precacheAndRoute(self.__WB_MANIFEST, { cacheKeyWillBeUsed: async ({ request }) => { const cleanedHeaders = new Headers(); // 遍历原请求头,过滤非ISO-8859-1字符 for (const [key, value] of request.headers.entries()) { cleanedHeaders.set(key, value.replace(/[^\x00-\xFF]/g, '')); } // 返回重新构造的合法请求 return new Request(request.url, { headers: cleanedHeaders, method: request.method, mode: request.mode, credentials: request.credentials, }); }, });
2. 规范 Electron 加载时的请求头
调用 loadURL 时显式指定合规的请求头,避免潜在的编码问题:
mainWindow.loadURL('https://example.test', { extraHeaders: 'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8' });
3. 升级 Workbox 版本
如果使用的是旧版 Workbox,该编码兼容问题可能已在新版本修复,尝试升级 workbox-precaching 到最新稳定版:
npm update workbox-precaching
4. 检查自定义请求头
排查应用中是否存在含非 ASCII 字符的自定义请求头(如中文标识、特殊符号),将其修改为仅包含 ISO-8859-1 范围内的字符。
内容的提问来源于stack exchange,提问作者Denis

