2012-04-20 9 views

Respuesta

3

Sí, asumiendo que quiere encontrar todas las @ font-faces especificadas en la hoja de estilo en lugar de usarlas en el documento HTML en sí.

Dada una hoja de estilo bastante estándar que se parece a esto:

@font-face { 
    font-family: 'Lobster12Regular'; 
    src: url('fonts/lobster_1.2-webfont.eot'); 
    src: url('fonts/lobster_1.2-webfont.eot?#iefix') format('embedded-opentype'), 
     url('fonts/lobster_1.2-webfont.woff') format('woff'), 
     url('fonts/lobster_1.2-webfont.ttf') format('truetype'), 
     url('fonts/lobster_1.2-webfont.svg#Lobster12Regular') format('svg'); 
    font-weight: normal; 
    font-style: normal; 

} 

@font-face { 
    font-family: 'AllerRegular'; 
    src: url('fonts/aller_std_rg-webfont.eot'); 
    src: url('fonts/aller_std_rg-webfont.eot?#iefix') format('embedded-opentype'), 
     url('fonts/aller_std_rg-webfont.woff') format('woff'), 
     url('fonts/aller_std_rg-webfont.ttf') format('truetype'), 
     url('fonts/aller_std_rg-webfont.svg#AllerRegular') format('svg'); 
    font-weight: normal; 
    font-style: normal; 

} 

@font-face { 
    font-family: 'AllerBold'; 
    src: url('fonts/aller_std_bd-webfont.eot'); 
    src: url('fonts/aller_std_bd-webfont.eot?#iefix') format('embedded-opentype'), 
     url('fonts/aller_std_bd-webfont.woff') format('woff'), 
     url('fonts/aller_std_bd-webfont.ttf') format('truetype'), 
     url('fonts/aller_std_bd-webfont.svg#AllerBold') format('svg'); 
    font-weight: normal; 
    font-style: normal; 

} 

@font-face { 
    font-family: 'AllerLight'; 
    src: url('fonts/aller_std_lt-webfont.eot'); 
    src: url('fonts/aller_std_lt-webfont.eot?#iefix') format('embedded-opentype'), 
     url('fonts/aller_std_lt-webfont.woff') format('woff'), 
     url('fonts/aller_std_lt-webfont.ttf') format('truetype'), 
     url('fonts/aller_std_lt-webfont.svg#AllerLight') format('svg'); 
    font-weight: normal; 
    font-style: normal; 

} 

h1 { 
    font-family: 'Lobster12Regular'; 
} 

h2 { 
    font-family: 'AllerRegular'; 
} 

A continuación, el código HTML siguiente (con Javascript en línea) será más o menos el truco:

<html> 

<head> 

<link rel="stylesheet" href="test.css"> 

</head> 

<body> 

<h1>Hello</h1> 
<h2>Hello</h2> 

<script type="text/javascript"> 

var pattern=/url\(.*?\)/g; 
for (var i=0;i<document.styleSheets[0].cssRules.length;i++) 
{ 
    var urls=document.styleSheets[0].cssRules[i].cssText.match(pattern); 
    if (urls) 
    { 
     for (var j=0;j<urls.length;j++) 
     { 
      alert(urls[j]); 
     } 
    } 
} 

</script> 

</body> 

</html> 

Con algunas salvedades:

En primer lugar, una de las principales formas de especificar @ font-face se basa en especificar el src dos veces, esta técnica solo recogerá el segundo src.

No he probado este navegador cruzado pero funciona en mi navegador y aparece un cuadro de alerta con cada url de fuente.

El código fijo [0] solo hace que se vea la primera hoja de estilo (en este ejemplo, solo hay una). Es razonablemente trivial escribir otro bucle para recorrer todas las hojas de estilo si es necesario, pero parece exagerado para este ejemplo.

+2

Tal vez sea obvio para usted, pero Quiero mencionar un problema de esto y de la solución [@ Orwellophile] (http://stackoverflow.com/a/19343013/2590616). Solo funcionará en las mismas hojas de estilo de dominio. Si intenta leer las reglas de una hoja de estilo en un dominio diferente, p. en un cdn, se encuentra con una política de dominio cruzado en Chrome y obtiene un error de script ("SecurityError: la operación es insegura") en Firefox. – RiZKiT

0

No, realmente no. Solo parece existir esta técnica: http://paulirish.com/2009/font-face-feature-detection/ para detectar si se puede usar @font-face, pero no para detectar qué fuentes están usando. Aparte de analizar todo el código CSS del lado del servidor (o al menos del lado del servidor), no hay forma de hacer lo que quiera, no solo con JS y jQuery. Lo siento por eso.

0

Esto es algo que acabo de escribir para mi propio uso, funciona bien con Chrome, no lo he probado con otros navegadores, pero parece bastante estándar para mí.

Requiere jquery e identificará todas las fuentes en uso y sus fuentes (si es webfonts).

Tenga en cuenta que no maneja adecuadamente las variaciones de una fuente (diferente versión 'negrita'), y tampoco puede manejar estilos con múltiples fuentes definidas (por ejemplo: font-family: fonta, fontb, fontc).

jQuery.fn.elementText = function() { 
    return $(this) 
      .clone() 
      .children() 
      .remove() 
      .end() 
      .text() 
      .replace(/^\s\s*/, '').replace(/\s\s*$/, '') 
      ; 
}; 

Font = function(family, src) { 
    // In order to properly categorise complex font setups, weight and style need to be 
    // considered as part of a unique font. (TODO) 
    this.family = family; 
    this.src = src; 
    this.weight = null; 
    this.style = null; 
}; 

Font.prototype.toString = function() { 
    return '[Font ' + this.family + ': ' + this.src + ']'; 
}; 


var fontNames = {}; 
var fontObjects = []; 

$(':visible').each(function (k, v) { 
    var $v = $(v); 
    var font; 
    if ($v.elementText().length) { 
     font = $v.css('font-family'); 
     // TODO: seperate by comma, remove quotes 
     fontNames[font] = font; 
    } 
}); 

for (var sheet=0; sheet < document.styleSheets.length; sheet++) 
for (var i=0; i<document.styleSheets[sheet].cssRules.length; i++) 
{ 
    var rule = document.styleSheets[sheet].cssRules[i]; 
    if (rule instanceof CSSFontFaceRule) { 
     if (fontNames[rule.style.fontFamily]) 
      fontObjects.push(
        new Font(rule.style.fontFamily, rule.style.src)); 
    } 
} 

fontObjects.forEach(function(v) { console.log(v.toString()); }); 

Salida de ejemplo (aquí se puede ver un ejemplo de lo que sucede cuando se tiene diferente 'negrita', define etc font-style 'cursiva'):

[Font 'ITC Legacy Sans Std': url(http://localhost/~admin/tmp/fonts/LegacySansStd-BookItalic.otf)] 
[Font 'ITC Legacy Sans Std': url(http://localhost/~admin/tmp/fonts/LegacySansStd-Book.otf)] 
[Font 'ITC Legacy Sans Std': url(http://localhost/~admin/tmp/fonts/LegacySansStd-MediumItalic.otf)] 
[Font 'ITC Legacy Sans Std': url(http://localhost/~admin/tmp/fonts/LegacySansStd-Medium.otf)] 
[Font 'ITC Legacy Sans Std': url(http://localhost/~admin/tmp/fonts/LegacySansStd-BoldItalic.otf)] 
[Font 'ITC Legacy Sans Std': url(http://localhost/~admin/tmp/fonts/LegacySansStd-Bold.otf)] 
[Font 'ITC Legacy Sans Std': url(http://localhost/~admin/tmp/fonts/LegacySansStd-Ultra.otf)] 
[Font 'Ocean Sans Std': url(http://localhost/~admin/tmp/fonts/OceanSansStd-LightIta.otf)] 
[Font 'Ocean Sans Std': url(http://localhost/~admin/tmp/fonts/OceanSansStd-Light.otf)] 
[Font 'Ocean Sans Std': url(http://localhost/~admin/tmp/fonts/OceanSansStd-Book.otf)] 
[Font 'Ocean Sans Std': url(http://localhost/~admin/tmp/fonts/OceanSansStd-SemiboldIta.otf)] 
[Font 'Ocean Sans Std': url(http://localhost/~admin/tmp/fonts/OceanSansStd-Semibold.otf)] 
[Font 'Ocean Sans Std': url(http://localhost/~admin/tmp/fonts/OceanSansStd-Bold.otf)] 
Cuestiones relacionadas