如何找出页面中包含的字体

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

本文关键字:包含 字体 何找出      更新时间:2023-09-26

我需要通过@font-face声明(无论是在外部样式表还是内联<style>元素中)获得页面上可用的所有字体名称的列表。这是一个脚本,将包括在我不控制的页面上。

理想情况下,我希望在不通过AJAX重新下载所有CSS文件并对其进行解析的情况下完成

但我不能使用API上的新文档,因为我需要它是合理的跨浏览器(如果可能的话,甚至IE7)。

有没有什么方法可以在不下载和解析CSS的情况下做到这一点?

我认为这将是一个开始:

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
    }
}

检查下面的代码,它可能有助于

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/