1

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?

callum
  • 34,206
  • 35
  • 106
  • 163
  • Related: http://stackoverflow.com/questions/9180184/access-css-file-contents-via-javascript – Derek Kurth Oct 02 '14 at 19:07
  • Looks like you could loop over document.styleSheets and look at the cssRules attribute (or "rules" for some browsers) for each sheet. – Derek Kurth Oct 02 '14 at 19:07

2 Answers2

1

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
    }
}
Derek Kurth
  • 1,771
  • 1
  • 19
  • 19
1

Check below code, it might help

var ruleFontName = [];
$.each(document.styleSheets, function(sheetIndex, sheet) {
    $.each(sheet.cssRules || sheet.rules, function(ruleIndex, rule) {
        if (typeof(rule.cssText) !== 'undefined' && rule.cssText.indexOf("font-face") !== -1) {
        var fntSrc = (rule.cssText. match(/src: *url\(([^;]+)\);/i) || ["", ""])[1];
        var fntName = (rule.cssText.match(/font-family: *([^;]+);/i) || ["", ""])[1];
        add(ruleFontName,fntSrc,fntName )
       }
    });
});

//checking if array values are not repeated


     function add(arr, src, name) {
            var foundName = arr.some(function (el) {
              return el.fntName === name;
            });
            var foundSrc = arr.some(function (el) {
              return el.fntSrc === src;
            });
            if (!foundName && !foundSrc) {
                arr.push({ fntName: name, fntSrc: src });
                console.log(arr);
            }

        }

JSFIDDLE : http://jsfiddle.net/hiteshbhilai2010/dpfpLyq1/47/

Hitesh
  • 4,098
  • 11
  • 44
  • 82