Search code examples
javascriptfontsfont-face

How to find out which fonts are included on a page?


I need to get a list of all font names that are available for use on the page via @font-face declarations (whether in external stylesheets or inline <style> elements). This is for a script that will be included on pages I do not control.

Ideally I'd like to do this without re-downloading all CSS files over AJAX and then parsing them.

But I can't use the new document.fonts API because I need this to be reasonably cross-browser (even IE7 if possible).

Is there any way to do this without downloading and parsing the CSS?


Solution

  • I think something like this would be a start:

    var sheets = document.styleSheets,
        sheet,
        rule,
        i, j;
    
    for (i = 0; i < sheets.length; i++) {
      sheet = sheets[i];
      for (j = 0; j < sheet.rules.length; j++) {
        rule = sheet.rules[j];
        if (typeof(rule.cssText) !== 'undefined' && rule.cssText.indexOf("font-face") !== -1) {
           console.log(rule.cssText); // you can parse the font name from rule.cssText here
        }
    }