2

我启动了一个在 instagram.com 上触发的 chrome 扩展程序。我想加载本地字体,但是当我打开扩展程序时,加载字体时出现此错误

GET chrome-extension://invalid/ net::ERR_FAILED

在加载字体时,在我的网络选项卡中,我有一个net::ERR_FAILED详细信息:

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

我按照这个解决方案加载本地字体https://stackoverflow.com/a/54957601/16813072

这是我的代码

清单.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",
  ],
  ...
}

应用程序.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';
  }
  `

我的代码看起来正确吗?


更新

似乎与chrome.runtime.getURL

在 app.tsx 中

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';
  }
`
4

1 回答 1

0

我们可以使用chrome.runtime.getURL API 来获取资源的 URL,然后我们可以在 font-face 的 src 中提供该 URL。

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';
  }
`

参考

于 2021-09-03T05:37:21.560 回答