During the rewrite of the cleanPages extension I stumbled over a problem, when I wanted to build in a font selector:
How can I determine, which fonts are installed on the computer?
AFAIK there is no way to retrieve the internal OS font list with an extension, so I had to find a reliable way to test which fonts are installed. There are many approaches to this problem in the web, may be the most famous is the mmmm-width-detection
. It works quite good if the fonts have distinctively different m widths - but some are not different enough, so it can give false positives.
and can read out all installed fonts, but it is a "no go" for an extension, as is Java.
Luckily I don't need to know all
installed fonts, but the most common, because the uncommon fonts are either pure decorative fonts, cheap rip-offs with bad quality or not complete enough and - even more luckily - I wrote a detection script for vendor prefixed CSS values some days ago which I could
rewrite to do the font detection.
You can test a fully working version of the script with some little extras here
Here is the basic code:
<title>Are these fonts installed?</title>
font: 13px/21px 'helvetica neue',arial,sans-serif;
margin: 15px auto;
var elem = document.getElementById('elem');
// get the font the browser really uses
var computed = window.getComputedStyle(elem);
// save the original style
var saved = (elem.style.fontFamily.getPropertyValue!=='undefined')?elem.style.fontFamily:'';
var fontList ='';
// array with font names to test against
var theFonts = ['Helvetica', '"Lucida Grande"', 'Tahoma', '"Microsoft Sans Serif"', 'Arial', /* here all the other font names */ ];
for (var i=0,fonts; fonts = theFonts[i++];)
elem.style.fontFamily = fonts;
// if the font name is identical with the name of the used font, show a test sentence
if (computed.fontFamily == fonts)
fontList += "<p style='font-family:"+fonts+"'>The Quick Brown Fox Jumps Over the Lazy Dog --- "+ fonts +" --- "+ i +"</p>\r\n";
fontList += "<p class='dimm'>Not available --- "+ fonts +" --- "+ i +"</p>\r\n";
elem.style.fontFamily = saved;
elem.innerHTML = fontList;
(c) 2011 by QuHno
The compatibility with older browsers is nonexistent, but the code works fine in Opera 11 (off course
), and with some minor quirks in Mozilla Firefox 4 and Internet Explorer 9 because they (again) don't follow the standards to 100%, even in standards mode. I could not test it with other browsers and I can't test it with Mac or Linux. I would appreciate if you could report it as working with other operating systems or other modern browsers.
Any hints of how to improve it are welcome!