Skip to content

Commit d9ab298

Browse files
committed
refactor: streamline font face URL handling in stylesheets by consolidating extraction and replacement logic
1 parent 5cec648 commit d9ab298

File tree

2 files changed

+9
-13
lines changed

2 files changed

+9
-13
lines changed

entrypoints/content/ui.ts

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -22,11 +22,7 @@ async function loadStyleSheet(shadowRoot: ShadowRoot) {
2222
)
2323
injectStyleSheetToDocument(shadowRoot, styleSheet)
2424
// font-face can only be applied to the document, not the shadow root
25-
const fontFaceStyleSheet = extractFontFace(styleSheet)
26-
// Content script stylesheets are parsed via new CSSStyleSheet() + replaceSync(),
27-
// so @font-face URLs (e.g. /fonts/Inter.woff2) resolve against the page URL
28-
// instead of the extension URL. Convert to absolute extension URLs.
29-
replaceFontFaceUrl(fontFaceStyleSheet, (url) => {
25+
const fontFaceStyleSheet = replaceFontFaceUrl(extractFontFace(styleSheet), (url) => {
3026
if (
3127
url.startsWith('data:')
3228
|| url.startsWith('moz-extension://')

utils/css.ts

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -64,18 +64,18 @@ export function createStyleSheetByCssText(cssText: string) {
6464
}
6565

6666
export function replaceFontFaceUrl(sheet: CSSStyleSheet, converter: (url: string) => string) {
67+
let cssText = ''
6768
for (const rule of sheet.cssRules) {
6869
if (rule instanceof CSSFontFaceRule) {
69-
const src = rule.style.getPropertyValue('src')
70-
if (src) {
71-
const newSrc = src.replace(/url\(['"]?([^'")]+)['"]?\)/g, (_match, url) => {
72-
return `url('${converter(url)}')`
73-
})
74-
rule.style.setProperty('src', newSrc)
75-
}
70+
cssText += rule.cssText.replace(/url\(['"]?([^'")]+)['"]?\)/g, (_match, url) => {
71+
return `url('${converter(url)}')`
72+
}) + '\n'
73+
}
74+
else {
75+
cssText += rule.cssText + '\n'
7676
}
7777
}
78-
return sheet
78+
return createStyleSheetByCssText(cssText)
7979
}
8080

8181
export function extractFontFace(sheet: CSSStyleSheet) {

0 commit comments

Comments
 (0)