背景
这个问题是由于 chrome@v130 版本更新后, chrome.runtime.getFile 返回的不再是 chromeid 的链接,而是一个 uuid4 的链接,因此导致了 csp 问题,让我们来看下解决方法
1. 更新 @crxjs/vite-plugin
更新 @crxjs/vite-plugin
到最新的 2.0.0-beta.28
版本
2. 添加一个 declarativeNetRequest
规则来禁止 CSP 头信息
// useCSP.ts
type Rule = any;
export function useCSP(hostMatch: string[], additionalRules?: Rule[]) {
(async () => {
let currentIndex = 0;
let r = await chrome.declarativeNetRequest.getDynamicRules(),
n = r.map((e) => e.id);
const rules = hostMatch.map((domain, index) => {
currentIndex = index + 1;
return {
id: currentIndex,
priority: 1,
action: {
type: "modifyHeaders",
responseHeaders: [
{ header: "Content-Security-Policy", operation: "remove" },
{
header: "Content-Security-Policy-Report-Only",
operation: "remove",
},
],
},
condition: {
regexFilter: domain,
resourceTypes: ["main_frame", "xmlhttprequest"],
},
} as Rule;
});
console.log(rules);
if (additionalRules && additionalRules.length > 0) {
additionalRules.map((rule) => {
rule.id = ++currentIndex;
rules.push(rule);
});
}
await chrome.declarativeNetRequest.updateDynamicRules({
removeRuleIds: n,
addRules: rules as any,
});
})();
}
在 background.js 中使用它
// background.js
useCSP(['https://google.com/*']);
在 manifest.json 中添加 declarativeNetRequest
权限
{
"permissions": [
"declarativeNetRequest"
]
}