Is it possible to get the filename of the rendered font of an element?
Example:
@font-face {
font-family: 'MyFont';
src: url('../../public/fonts/MyFont-Bold.woff2') format('woff2');
font-weight: bold;
font-style: normal;
}
@font-face {
font-family: 'MyFont';
src: url('../../public/fonts/MyFont-Italic.woff2') format('woff2');
font-weight: normal;
font-style: italic;
}
.my-font-bold {
font-family: 'MyFont';
font-weight: bold;
font-style: normal;
}
<p className="my-font-bold"></p>
In this example I would like to get ../../public/fonts/MyFont-Bold.woff2
of the element (because it has font-weight bold and font-family = "MyFont" thanks to the className "my-font-bold").
PS: I would like to do this to make font Vitest tests.
CodeSandbox: https://codesandbox.io/p/sandbox/magical-flower-q87vz7?file=%2Fapp%2Ffont.test.tsx%3A27%2C2
2
Answers
In Javascript it is definitely possible. You just need to leverage the
getComputedStyle
to achieve that.Steps to achieve the requirement:
p
tag is using.url
and return the result else returnnull
.Code implementation:
Writing the test for the above function:
There is no direct way to access the filename of the rendered font in a web browser. JavaScript running in a browser is intentionally sandboxed and doesn’t have access to low-level system file details for security reasons. If you need to verify which font is being used on a particular element for testing purposes, you can examine its computed styles using JavaScript.
The following example will check the font-family for an element: