背景

这个问题是由于 chrome@v130 版本更新后, chrome.runtime.getFile 返回的不再是 chromeid 的链接,而是一个 uuid4 的链接,因此导致了 csp 问题,让我们来看下解决方法

1. 更新 @crxjs/vite-plugin

更新 @crxjs/vite-plugin到最新的 2.0.0-beta.28 版本

2. 添加一个 declarativeNetRequest 规则来禁止 CSP 头信息

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
//  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 中使用它

1
2
//  background.js
useCSP(['https://google.com/*']);

在 manifest.json 中添加 declarativeNetRequest 权限

1
2
3
4
5
{
  "permissions": [
    "declarativeNetRequest"
  ]
}