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

基于React+Webpack的Chrome扩展:通过Content Script添加自定义字体的问题

在React+Webpack构建的Chrome扩展中通过Content Script加载自定义字体的正确方案

核心思路说明

将字体文件放在扩展的public目录(或打包后可访问的资源目录),通过Chrome扩展的资源访问机制声明可访问权限,再用正确路径引用字体——这是完全可行的标准方案,以下是具体实现步骤:

步骤1:存放字体文件

把字体文件(如some-font.ttf、some-font.woff2)放入项目的public/fonts目录。如果是自定义Webpack配置,需确保该目录会被完整复制到打包后的扩展输出目录(Create React App 默认自动处理public目录资源)。

步骤2:配置manifest.json的资源访问权限

在manifest.json中添加web_accessible_resources字段,声明字体资源允许被注入的网页访问:

"web_accessible_resources": [
  {
    "resources": ["fonts/*.ttf", "fonts/*.woff2"], // 匹配你的字体文件类型
    "matches": ["<all_urls>"] // 可替换为特定目标网站域名,如"https://example.com/*"
  }
]

步骤3:正确引用字体(两种方式)

方式1:通过Content Script注入静态CSS

  1. 创建单独的content.css文件,写入@font-face规则:
@font-face {
  font-family: "MyFont";
  src: url("chrome-extension://__MSG_@@extension_id__/fonts/some-font.ttf") format("truetype"),
       url("chrome-extension://__MSG_@@extension_id__/fonts/some-font.woff2") format("woff2");
  font-weight: normal;
  font-style: normal;
  font-display: swap; // 优化字体加载体验
}

/* 定义需要应用字体的样式 */
.custom-font-text {
  font-family: "MyFont", sans-serif !important;
}

其中__MSG_@@extension_id__是Chrome扩展内置占位符,会自动替换为你的扩展ID,无需硬写。

  1. 在manifest.json的content_scripts中注入该CSS:
"content_scripts": [
  {
    "matches": ["<all_urls>"], // 对应目标网站
    "css": ["content.css"],
    "js": ["content.js"] // 若需注入React组件,填写打包后的Content Script JS路径
  }
]

方式2:在React组件中动态注入字体样式

如果需要在React组件内动态加载字体,可通过chrome.runtime.getURL()获取字体绝对路径,在组件挂载时生成style标签注入:

import { useEffect } from 'react';

const CustomFontComponent = () => {
  useEffect(() => {
    const styleEl = document.createElement('style');
    const fontUrl = chrome.runtime.getURL('fonts/some-font.ttf');
    const fontWoff2Url = chrome.runtime.getURL('fonts/some-font.woff2');
    
    styleEl.textContent = `
      @font-face {
        font-family: 'MyFont';
        src: url('${fontWoff2Url}') format('woff2'),
             url('${fontUrl}') format('truetype');
        font-weight: normal;
        font-style: normal;
      }
      .custom-text {
        font-family: 'MyFont', sans-serif !important;
      }
    `;
    
    document.head.appendChild(styleEl);
    return () => document.head.removeChild(styleEl);
  }, []);

  return <div className="custom-text">使用自定义字体的内容</div>;
};

export default CustomFontComponent;

关键注意事项

  • 尽量提供多种字体格式(如woff2、ttf),woff2体积更小且兼容性更好。
  • 必须配置web_accessible_resources,否则浏览器会阻止网页访问扩展内的字体资源,导致加载失败。
  • 避免硬写扩展ID,使用__MSG_@@extension_id__或chrome.runtime.getURL()保证扩展打包后正常运行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 08:13:13