Get the exact font of the displayed text in the browser, possibly with a browser extension

I know that you can get the font-family value on window.getComputedStyle() , but this is not always the exact font used by the browser for rendering. For example, if a given text contains (multilingual) text, the font family is not migrated, the browser partially displays the text with the system font.

If you look at the developer’s built-in web tool, in either Chrome or Firefox, they have a small area to display (the Rendered Fonts panel on the Chrome tab or the Fonts tab in Firefox) the exact fonts that are used. For Firefox, I think this code is used and seems to be calling the internal API.

I am looking for any DOM-compatible (or vendor-specific) way to get the exact font from JavaScript land or another. If this means writing a browser extension / extension to provide an API / injection of information / anything for the page included in the code, this is the worst case, but acceptable.

+5
source share
1 answer

You can use hacking: the main idea is to compare the size of inline elements with some given fonts. The full font-family value should be used; the other is just one font family. Here is a proof of concept that works very well.

 // Look at the fiddle for full working code function createFontTester(fontFamily) { var container = document.createElement('div'); var tester = document.createElement('div'); container.style.position = 'absolute'; container.style.overflow = 'auto'; container.style.visibility = 'hidden'; tester.style.fontFamily = fontFamily; tester.style.display = 'inline'; tester.style.visibility = 'hidden'; // The size should be big enough to make a visual difference tester.style.fontSize = '100px'; // Reset and prevent line breaks tester.style.fontWeight = 'normal'; tester.style.fontStyle = 'normal'; tester.style.letterSpacing = 'normal'; tester.style.lineHeight = 'normal'; tester.style.whiteSpace = 'nowrap'; document.body.appendChild(container); container.appendChild(tester); return tester; } 

Please note that some fonts are so similar that most characters occupy the same space. Take Helvetica and Arial, for example: the width of the characters is basically the same, the height is slightly different, so I used a large font size.

This method is probably not bulletproof, but it works for all font families that I could think of.

Update . I made this small library on Github that handles even more use cases.

-1
source

Source: https://habr.com/ru/post/1232575/


All Articles