Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the exact font of a rendered text in the browser, maybe with a browser extension [duplicate]

I know you can get the font-family value by window.getComputedStyle() but that's not always exactly the font that is used by a browser to render. For example, if the given text contains the (multi-lingual) text the font family does not carry, the browser renders the text partially with the system font.

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

I'm looking for any DOM-compliant (or vendor-specific) way to get the exact font from the JavaScript land or else. If that means writing a browser extension/add-on to provide API/inject info/whatever for the in-page code to access, that's the worst case, but acceptable.

like image 730
beatak Avatar asked Sep 29 '15 21:09

beatak


1 Answers

You can with a hack : the main idea is to compare the size of inline elements with some given fonts. One should use the complete font-family value, another only a single font-family. Here's a proof of concept which work pretty 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;
}

Note that some fonts are so similar that most characters take the same space. Take Helvetica and Arial for instance : character width is mostly the same, height is slightly different so I used a large font-size.

This method is probably not bullet-proof but it work for every font-families I could think of.

Update : I've made this little library on Github which handle even more use cases.

like image 103
Julien Cabanès Avatar answered Oct 17 '22 01:10

Julien Cabanès