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

Chrome扩展加载Google Fonts遇CSP限制,字体无法生效求助

解决方案:打包本地字体绕开页面CSP限制

你的问题核心是:内容脚本无法修改目标页面的Content Security Policy,页面自身的CSP(比如Twitter的font-src 'self' https://*.twimg.com)优先级远高于你插入的meta标签,而Manifest V3里的extension_pages CSP配置只针对扩展自身的页面(弹窗、选项页等),对内容脚本运行的页面上下文无效。

直接上可行方案:

步骤1:下载并打包字体文件到扩展

  1. 下载Roboto Mono的300/400/500权重woff2格式字体文件。
  2. 在扩展根目录创建fonts文件夹,把下载的字体文件放入,比如:
    • RobotoMono-Light.woff2(300权重)
    • RobotoMono-Regular.woff2(400权重)
    • RobotoMono-Medium.woff2(500权重)

步骤2:创建本地字体样式文件

在扩展根目录新建fonts.css,内容如下:

@font-face {
  font-family: 'Roboto Mono';
  font-weight: 300;
  font-style: normal;
  src: url('fonts/RobotoMono-Light.woff2') format('woff2');
}
@font-face {
  font-family: 'Roboto Mono';
  font-weight: 400;
  font-style: normal;
  src: url('fonts/RobotoMono-Regular.woff2') format('woff2');
}
@font-face {
  font-family: 'Roboto Mono';
  font-weight: 500;
  font-style: normal;
  src: url('fonts/RobotoMono-Medium.woff2') format('woff2');
}

步骤3:配置Manifest V3允许资源访问

在manifest.json中添加web_accessible_resources字段,让目标页面可以访问扩展内的字体和样式文件:

{
  // 其他配置...
  "web_accessible_resources": [
    {
      "resources": ["fonts/*", "fonts.css"],
      "matches": ["https://twitter.com/*", "https://linkedin.com/*", "https://facebook.com/*"]
    }
  ]
}

步骤4:修改内容脚本加载本地样式

替换原来的远程Google Fonts加载代码,改为加载扩展内的fonts.css:

(function() {
  const styleLink = document.createElement('link');
  styleLink.href = chrome.runtime.getURL('fonts.css');
  styleLink.rel = 'stylesheet';
  document.head.appendChild(styleLink);
})();

步骤5:应用字体到你的扩展元素

现在你的扩展DOM元素可以直接使用该字体,比如:

.your-extension-element {
  font-family: 'Roboto Mono', monospace;
  font-weight: 400; /* 根据需要选300/400/500 */
}

为什么这个方案可行?

  • 本地字体属于扩展自身资源,通过web_accessible_resources授权后,目标页面的CSP规则会允许加载这些资源(符合'self'的可信范围)。
  • 完全绕开了外部字体源的CSP限制,不需要修改目标页面的任何规则。

内容的提问来源于stack exchange,提问作者Anil Kumar

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 22:07:41