JavaScript/CSS Font Detector

JavaScript code to detect available availability of a particular font in a browser using JavaScript and CSS.

I wrote a JavaScript code which can be used to guess if a particular font is present in a machine. This may be help of desktop-like web application developers when they want to provide different skins or fonts preferences to their users. This may also be help for blog skin designers which can provide different fonts for different users based on the list of fonts on their machine. Designers don’t have to rely on the most common fonts like Arial, Verdana or Times New Roman. Since increasing number of users have modern PC with new operating system / applications, they may very well have a wide array of other common fonts in their machine.

How does it work?

This code works on the simple principle that each character appears differently in different fonts. So different fonts will take different width and height for the same string of characters of same font-size.

Widths of same text in different fonts

We try to create a string with a specified font-face. If the font-face is not available, it takes up the font-face of the parent element. We then compare the width of the string with the specified font-face and width of the string with the font-face of the parent element, if they are different, then the font exists, otherwise not.

The string which we will use to generate the widths can be anything. But I guess we use ‘m’ or ‘w’ because these two characters take up the maximum width. And we use a trailing ‘l’ so that the same width fonts-faces can get separated based on the width of l character.

I have tested it on Firefox 2, 3, 3.5 IE 6, IE 7, Opera 9, Opera 10.

Update Now works on Opera 9.10. It required to execute the script after its completely loaded. I guess, Opera cannot calculate the offset width until all the parents are completely loaded.

Update (10-Jul-09) Fixed the Tests failing on Firefox 3 issue. changed comparison font to serif from sans-serif, as in FF3.0 font-face of child element didn’t fallback to font-face of parent element if the font-face of child element is missing.

Download

Get the JavaScript code here.

Released under CC Attribution-ShareAlike 2.5
Released under Apache Software License.

You can also see Lemmi’s version of the script as Prototype plug-in here.

Demo

You can test any Font here:

// Usage
var detective = new Detector();
alert(detective.test('font name'));

Fonts on your computer

This table below shows which fonts are present on your system. (I have listed some of the most common and some uncommon fonts.)

Johan Sundström has presented this data in a more interesting and cool layout here. Thanks Johan!

Font Name Width Height Detected?

• • •

70 Responses to JavaScript/CSS Font Detector

  1. Pingback: Different sizes for alternative fonts? - Webforumz.com

  2. Ellen says:

    There is a problem.

    According to the list you offer, it must only use the pc names for the fonts … I am on a mac (OS X 10.4) and have Bookman Oldstyle, Bradley Hand, Century Schoolbook, Garamond and some others (including “default” )that your script returned as false.

    In addition, even with some that it returned true, the associated text did not appear in the specified font.

    I really like this idea, at least until CSS3 font: url(); gets implemented.

  3. Lalit says:

    @Ellen, you are on FF3?

  4. Pingback: rel=me » Blog Archive » Font detection with Javascript and Flash

  5. Pingback: Javascript猜测

  6. Francois Dagorn says:

    I’m was looking for a way to detect wether or not stix fonts are installed
    on a laptop. I’ve found your script, good idea !
    Unfortunately under vista it seems to always answer ‘true’ even if the
    font is not installed !

    Any idea ?

    Cheers.

    François

  7. Lalit says:

    @François
    You are right, I breaks on Vista/FF3
    Will fix over this weekend.

  8. Ravi says:

    I tried it on Chrome/Vista. It always shows true too. But some how it seems to show correctly on first run. That is close your browser and run it first. If you refresh, than it starts showing true for everything!

  9. Dana says:

    Well It works great on my IE 7.0.5730.11
    But not in Crome 0.2.149.29 and FireFox 3.0.1 :) geat idea though

  10. doug says:

    Hi Lalit

    I am hoping you script will work for our site. We have designed 2008.vensystems.co.uk using Calibri – now we’ve tested the font-family, we’ve realised our menu’s and tables do not allow for the additional width of all other sans-serif fonts. Would your code be able to detect and replace Calibri with another font set to a different size?

    Many thanks in advance,

    Doug

  11. Rodrigo says:

    This approach is quite innovative!

  12. Pingback: Flipping Typical / Melodycode.com - Life is a flash

  13. Yoan says:

    I would be very nice to collect the UA and OS and do a little survey of the available fonts in which we can rely on.

    I.e. on Opera mobile, I see only sans-serif, monospace and courier new as detected (which seems accurate by the way).

    Cheers,

  14. Pingback: A new popular font browser Flipping Typical - WittySparks

  15. Pingback: links for 2009-01-13

  16. Pingback: Javascript/CSS detect browser fonts « Louis Ramos’ Blog

  17. David Ruiz says:

    Cool! Great idea compare font sizes. But I had problems with Firefox:

    When Firefox don’t find the font, not always shows ‘sans-serif’ type. Changing next line solves it:
    f[0] = s.style.fontFamily = font;
    to
    f[0] = s.style.fontFamily = font + “, sans-serif”;

    Anyway, good work.

  18. Pingback: Dave Ruiz blog » Fuentes no estandar en tu web con jQuery

  19. Pingback: Filpping Typical: What The Fonts Installed In Your Computer Looks Like on Your Browser | Orangeinks

  20. Pingback: classid - bytes

  21. Pingback: classid: get list of installed fonts - bytes

  22. Pingback: Tagz | "JavaScript / CSS Font Detector - Detect fonts available in a browser | lalit.org" | Comments

  23. Matt says:

    It’s a great idea, and it works on my IE7. Unfortunately, this does not seem to work on Firefox 3.5 (Mac or Win) or Safari (Mac) – it is listing everything as “True.”

  24. Lalit says:

    Fixed the Firefox bug. Now works on Firefox 3.0 and 3.5
    Also changed the API a bit, test() function returns boolean instead of an array. For detailed info use detailedTest() instead.

    Thanks @David Ruiz, @François, @Dana

  25. Pingback: Elsewhere, on August 14th - Once a nomad, always a nomad

  26. mvg says:

    JavaScript / CSS Font Detector – Detect fonts available in a browser | lalit.org great article thank you.

  27. Pingback: Of stacks and faces | Angry Monkeys

  28. kurye says:

    JavaScript / CSS Font Detector – Detect fonts available in a browser | lalit.org great article thank you.

  29. Jean-Sebastien Dussault says:

    Had trouble making the dowloadable script work in IE (8) as it was returning a false negative. The script embedded on this page worked fine, though, so I had a look at the difference.

    The downloadable version was using “sans” as a comparator, even if the comments following it said “serif font used as a comparator”. Changed it to serif, and everything was A-OK.

    BTW, the version using “sans” worked fine under FF 3.5.3.

  30. Mark says:

    I have looked in to your script as I have built me own script sort of like this but less complex.

    Your script doesn’t detect (accurately) if Calibri is in fact installed. It always evalutates as false (Windows Vista Business Edition IE 6, 7, 8) UNLESS you campare it using Arial. Then it will return it more accurately. Is there a good reason why you used “sans”?

    I found that it is only an issue with IE (most of the market share).

    Let me know what you think.

  31. Pingback: Detecta si una fuente está disponible desde Javascript | aNieto2K

  32. Pingback: Detecta si una fuente está disponible desde Javascript : Blogografia

  33. Pingback: Detecta si una fuente está disponible desde Javascript

  34. _asterix_ says:

    Wow! This is a gerat Solution. Thank you very much.

  35. Emlyn says:

    OS X 10.5 using FF 3.5.7 and all testing works fine (including Calibri).

    Great temp fix until CSS3 is in play–tx.

  36. Woodrow says:

    Great stuff! But:

    the detector faultily detects that “Times New Roman” is not installed. This is because you use “serif” as a comparison-font (which is basically the same as TNR) but only check for one of these two fonts here:
    <>

    Based on the comment that can be found there (“to set arial and sans-serif true”) I bet that a) you used “Arial” as a comparison-font for some time and b) you had the same issue then as well. So I guess you know what I mean ;^)

  37. Woodrow says:

    great … (-.-’ )

    I was talking about this line:

    if (font == “serif”)

  38. Hi, I came across this article while searching for help with JavaScript. I’ve recently changed browsers from Safari to Microsoft IE 6. Now I seem to have a problem with loading JavaScript. Every time I browse page that needs Javascript, the page freezes and I get a “runtime error javascript.JSException: Unknown name”. I cannot seem to find out how to fix it. Any help is very appreciated! Thanks

  39. Pingback: ¿Y quién diablos es @font-face? | Todowebhosting.com - ..::HOSTING - DISEÑO WEB - FACTURACIÓN ELECTRÓNICA

  40. Lemmi says:

    First, your script is a great idea to find out which font is installed. Keep going!
    I often work with the Framework Prototype, so here is a class based on the Prototype methods.

    var Checkfont = Class.create({
        checkedFonts: new Hash(),
        testString: 'mmmmmmmmmmlilg',
        testFontSize: '72px',
        standardFont: 'serif',
     
        initialize: function() {
            this.body = document.body;
            this.span = new Element('span').hide();
     
            this.body.insert(this.span);
            this.defaultDimensions = this._getFontDimensions(this.standardFont);
        },
     
        test: function(font) {
            font = font.toLowerCase();
     
            var alreadyChecked = this.checkedFonts.get(font);
            if (!Object.isUndefined(alreadyChecked)) {
                return alreadyChecked;
            }
     
            this.testDimensions = this._getFontDimensions(font);
     
            var test = true;
            if (font != this.standardFont) {
                test = (this.testDimensions.width != this.defaultDimensions.width
                    || this.testDimensions.height != this.defaultDimensions.height);
            }
            this.checkedFonts.set(font, test);
            return test;
        },
     
        _getFontDimensions: function(font) {
            this.span.setStyle({
                fontFamily: font,
                fontSize: this.testFontSize
            }).update(this.testString);
            var fontDimensions = this.span.getDimensions();
            this.span.update();
            return fontDimensions;
        }
    });
  41. Pingback: viplog

  42. Lalit says:

    Thanks Lemmi for the Prototype version of the script.
    Cheers!

  43. Pingback: ¿Y quién diablos es @font-face?

  44. Darryl Booms says:

    May I suggest adding single quotes around the font name when setting for the test font. Firefox 3.6.3 at least is omitting the “font-family: ” part if there are spaces in the name for at least the “Free 3 of 9 Extended” from http://www.barcodesinc.com/free-barcode-font/ and may be playing a part in some of the other issues too. Plus it still detects just fine (on Firefox 3.6.3 & IE 8) with the extra single quotes.

    f[0] = s.style.fontFamily = font; // Name of the font
    changes to
    f[0] = s.style.fontFamily = “‘” + font + “‘”; // Name of the font

  45. Dean Brettle says:

    Hi Lalit,

    Where you have:

    f = debug(font);

    it should be:

    var f = debug(font);

    to avoid polluting the global namespace.

    Thanks for the script!

  46. Pingback: Nothing to See Here – Just a Redesign

  47. Pingback: Schriftart abfragen - php.de

  48. Bronius says:

    I think this font detector is great for installed fonts but doesn’t seem to do it for fonts downloaded by @font-face, does it? This applies to folks who have disabled font downloading in IE security options.

    Thanks for the great post.

  49. Bronius says:

    [edit] Oh snap! I was testing incorrectly. YES, this font detector detects even when a font is downloaded to the client browser using the @font-face css rule and effectively provides a work-around for Internet Explorer users whose security settings disable font downloads. THANK YOU :D

  50. Bronius says:

    [edit] Me again– Looks like I can get it to work in IE only– Firefox detects local fonts but not @font-face fonts (it appears). Can anyone else confirm?

  51. Гость says:

    document.getElementsByTagName(“BODY”)
    returns nothing :)

    Bronius, for IE use eot

  52. Pingback: Web Typography: 100 Educational Resources, Tools and Techniques - Smashing Magazine

  53. Pingback: Web Typography: Educational Resources, Tools and Techniques

  54. Pingback: Detección de fuentes disponibles con Javascript « Zarkiel Program's – Programación y más…

  55. Pingback: Chris Graham – Web Typography: Educational Resources, Tools and Techniques

  56. Pingback: Little Web Geek | Web Typography: Educational Resources, Tools and Techniques

  57. Pingback: Web Typography: Resources, Tools & Techniques « The Creative Portfolio of Mark-Anthony

  58. Lucas says:

    Try this update (detailed test now returns an object, instead of a “magic numbers” array)

    /**
    * Detect availability of particular fonts
    *
    * Author : Lalit Patel
    * Website: http://www.lalit.org/lab/jsoncookies
    * License: Creative Commons Attribution-ShareAlike 2.5
    * http://creativecommons.org/licenses/by-sa/2.5/
    * Contributor: Lucas Sandery
    * Updated: 2010-12-03
    *
    * Usage:
    * var d = new Detector();
    * exists = d.test('Courier', true);//second param specifies font as fixed width
    * exists = d.test('Times New Roman');
    * results = d.detailedTest('Courier', true);
    * results = d.detailedTest('Times New Roman');
    */
    var Detector = function() {
    this.body = document.getElementsByTagName('BODY')[0];
    this.div = document.createElement('DIV');
    this.div.style.visibility = 'hidden';
    this.span = document.createElement('SPAN');
    this.div.appendChild(this.span);
    this.span.style.fontSize = '72px';
    this.span.innerHTML = 'mmmmmmmmmmxxxxxxxxxxiiiiiiiiii';
    this.generic = {
    serif: true,
    'sans-serif': true,
    cursive: true,
    fantasy: true,
    monospace: true
    };
    this.detailedTest = function(font, isFixedWidth) {
    var defaultFont = isFixedWidth ? 'serif' : 'monospace';
    this.div.style.fontFamily = defaultFont;
    this.span.style.fontFamily = '';
    this.body.appendChild(this.div);
    var defaultWidth = this.span.offsetWidth;
    var defaultHeight = this.span.offsetHeight;
    if (font.toLowerCase() != defaultFont)
    this.span.style.fontFamily = this.generic[font] ? font : "'" + font + "', " + defaultFont;
    var f = {
    width: this.span.offsetWidth,
    height: this.span.offsetHeight
    };
    this.body.removeChild(this.div);
    f.name = font;
    f.testedAsFixedWidth = !!isFixedWidth;
    f.exists = font.toLowerCase() == defaultFont || f.width != defaultWidth || f.height != defaultHeight;
    return f;
    }
    this.test = function(font, isFixedWidth) {
    var f = this.detailedTest(font);
    return f.exists;
    }
    }

  59. Pingback: Tipografías en tu web. @font-face | MusaConfusa

  60. Pingback: Anonymous

  61. KJ says:

    Your script is returning true when I check to see if my computer has helvetica, which I do not have helvetica on my computer.
    Win7 FF3.6

  62. Pingback: Web App Strategy Marginally Flawed « Shiny Pebbles…

  63. homie says:

    Until today I had one instance of Detector and tested few fonts on it. It was wrong. I was getting some false positives. I needed to create new instance for next check.

    Also there is a bug (at least in Firefox) that some certain fonts (for example Brook 23 or Bauhaus 93) need to be passed to fontFamily with ” “. Other way you get false negative.

  64. Rupi says:

    Thanks, great script !!!
    It might be usefull some time

  65. Pingback: SharePoint branding: automatically resizing backup fonts on browser capability | Yaroslav Pentsarskyy on SharePoint Development

  66. Pingback: xhtml css templates – JavaScript/CSS Font Detector › lalit.org | XHTML CSS - Style sheet and html programming tutorial and guides

  67. I did a different take on this, using a custom made font that guarantees impossibly small widths for text, loaded via @font-face, and then comparing two strings, one typeset with the custom font, and styled with “font-family: desiredfont, customfont”. If the widths are the same, the font is not supported. This makes it a yes/no solution rather than a percentual likelihood one. A demonstrator of it is up on http://pomax.nihongoresources.com/downloads/fonttest

  68. Pingback: Is there a way to hide text if a font is unavailable? | SeekPHP.com

  69. moto kurye,istanbul kurye,acil kurye says:

    I delight in, lead to I found just what I was having a look for. You have ended my four day lengthy hunt! God Bless you man. Have a great day. Bye

  70. Pingback: Fonts by xtophe - Pearltrees

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">