¿Hay alguna forma de enumerar todas las URL @ font-face (URL de fuente web) de una página HTML determinada mediante JavaScript o JQuery?Enumerar URL de fuente @ font utilizando Javascript/JQuery
Respuesta
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.
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.
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)]
- 1. Cómo usar Fuente Web con @ font-face
- 2. cómo configurar tamaño de fuente font-family
- 3. ¿Por qué no definir font-weight o font-style en @ font-face, Font Squirrel?
- 4. ¿Es posible utilizar fuentes personalizadas, utilizando font-face?
- 5. @ font-face Fuente en la lista negra
- 6. Cambiar fuente de WebView utilizando CSS; archivo de fuente en la carpeta de activos. (problema)
- 7. Usando @ font-face para Segoe UI font
- 8. @ font-face no funciona
- 9. variante de fuente: small-caps; muestra diferentes tamaños de fuente utilizando Chrome o Firefox
- 10. @ font-face representación gruesa
- 11. UIPickerView Font
- 12. font-size: 62,5% vs. font-size: 10px
- 13. Problemas de representación de fuente de Windows con @ font-face en CSS
- 14. registrar una fuente con Raphael usando CSS3 @ font-face
- 15. @ font-face vs Cufon
- 16. @ font-face HattoriHanzoLight no funciona
- 17. CSS: @ font-face anti aliasing
- 18. El uso de CSS @ font-face con el iPad/iPhone
- 19. Nueva prueba de balas @ sintaxis font-face utilizando datos URI en compás
- 20. Firefox 3.5 en Mac y @ font-face
- 21. font-face cambiando a través de JavaScript
- 22. Enumerar caja de la perspectiva utilizando Visual Studio
- 23. ¿Cómo funciona @ font-face?
- 24. Matplotlib, fuente consistente utilizando látex
- 25. SASS y @ font-face
- 26. Eclipse Indigo Font Changed
- 27. Emacs buffer-local font
- 28. @ font-face no funciona en cromo
- 29. CSS font-face emite
- 30. @ font-face src: local - ¿Cómo usar la fuente local si el usuario ya la tiene?
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