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_
相关产品推荐
相关产品推荐

