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

Chrome扩展在Instagram站点加载本地字体时出现chrome-extension://invalid/报错

Chrome扩展在Instagram站点加载本地字体报错问题

我开发了一款运行在instagram.com站点的Chrome扩展,尝试加载本地字体时,在字体加载阶段触发如下报错:
GET chrome-extension://invalid/ net::ERR_FAILED
网络面板中该字体请求的详情如下:

General
Request URL: chrome-extension://invalid/
Referrer Policy: strict-origin-when-cross-origin
Request Headers
Provisional headers are shown
DNT: 1
Origin: https://www.instagram.com

原始代码

manifest.json配置

{
  ...
  "content_scripts": [
    {
      "matches": ["*://*.instagram.com/*"],
      "js": ["content_script.js"],
      "run_at": "document_start",
      "web_accessible_resources": [ "assets/ClashGrotesk-Variable.ttf" ]
    }
  ],
  "web_accessible_resources": [
    "assets/inject.js",
    "assets/ClashGrotesk-Variable.ttf",
  ],
  ...
}

注:content_scripts下声明的web_accessible_resources属于冗余配置,该字段仅声明在manifest.json顶层才会生效。

app.tsx代码(使用styled-components开发)

const GlobalStyle = createGlobalStyle`
  @font-face {
    font-family: 'ClashGrotesk-Variable';
    src: url('chrome-extension://__MSG_@@extension_id__/assets/ClashGrotesk-Variable.ttf');
    font-weight: 200 700;
    font-display: swap;
    font-style: normal;
  }

  html body {
    font-family: 'ClashGrotesk-Variable';
  }
  `

问题原因

__MSG_@@extension_id__是Chrome扩展的静态占位符,仅能在扩展的CSS文件、manifest.json配置中被自动解析替换,在styled-components的JavaScript模板字符串中运行时不会被识别替换,因此生成了无效的chrome-extension://invalid/请求地址,触发加载失败错误。

解决方案

使用Chrome扩展提供的运行时API chrome.runtime.getURL生成正确的资源路径,修正后的代码如下:

const url = chrome.runtime.getURL('assets/ClashGrotesk-Variable.ttf')
const GlobalStyle = createGlobalStyle`
  @font-face {
    font-family: 'ClashGrotesk-Variable';
    src: url(${url});
    font-weight: 200 700;
    font-display: swap;
    font-style: normal;
  }

  html body {
    font-family: 'ClashGrotesk-Variable';
  }
`

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 05:00:01