How to detect which one of the defined font was used in a web page?

Pat picture Pat · Aug 3, 2008 · Viewed 48.9k times · Source

Suppose I have the following CSS rule in my page:

body {
    font-family: Calibri, Trebuchet MS, Helvetica, sans-serif;
}

How could I detect which one of the defined fonts were used in the user's browser?

For people wondering why I want to do this is because the font I'm detecting contains glyphs that are not available in other fonts. If the user does not have the font, then I want it to display a link asking the user to download that font (so they can use my web application with the correct font).

Currently, I am displaying the download font link for all users. I want to only display this for people who do not have the correct font installed.

Answer

MojoFilter picture MojoFilter · Aug 3, 2008

I've seen it done in a kind of iffy, but pretty reliable way. Basically, an element is set to use a specific font and a string is set to that element. If the font set for the element does not exist, it takes the font of the parent element. So, what they do is measure the width of the rendered string. If it matches what they expected for the desired font as opposed to the derived font, it's present. This won't work for monospaced fonts.

Here's where it came from: Javascript/CSS Font Detector (ajaxian.com; 12 Mar 2007)