John Pettitt
John Pettitt

Reputation: 659

detecting in-use @font-face via javascript

I need to sniff the formatting for a <p> so I can pass the info to an <iframe> and match formats.

I can get the font face using jQuery

var font = $("p").css('font-family');
var fsiz = $("p").css('font-size');

However if the font-family is a web font - eg "Open Sans" I also need to find the src for the @font-face rule that loaded it.

I have no idea how to do that.

Upvotes: 1

Views: 3583

Answers (3)

Tom
Tom

Reputation: 7091

As a small improvement on Paul S's answer, I've included nested objects with the font weight and style as keys, to retrieve all versions of a font.

function getFonts (obj) {
    var o = obj || {},
        sheet = document.styleSheets,
        rule = null,
        i = sheet.length, j;
    while( 0 <= --i ){
        rule = sheet[i].rules || sheet[i].cssRules || [];
        j = rule.length;
        while( 0 <= --j ){
            if( rule[j].constructor.name === 'CSSFontFaceRule' ){
                if (!(rule[j].style.fontFamily in o)) o[ rule[j].style.fontFamily ] = Object.create(null);
                o[ rule[j].style.fontFamily ][ rule[j].style.fontWeight + '-' + rule[j].style.fontStyle ] = rule[j].style.src;
            };
        }
    }
    return o;
}

Upvotes: 0

Roemer
Roemer

Reputation: 1271

I adapted the chosen solution to work as well in IE and FF, also Safari on iOs. The chosen solution only worked in Chrome. (Alas I cannot - yet - add comments to that solution, that's why I put it in a seperate solution.)

function getFonts (obj) {
    var o = obj || {},
        sheets = document.styleSheets,
        rules = null,
        i = sheets.length, j;
    while( 0 <= --i ){
        rules =  sheets[i].cssRules || sheets[i].rules || []; // I swapped those two, IE would go wrong
        j = rules.length;
        while( 0 <= --j ){
            if( rules[j].toString() == "[object CSSFontFaceRule]" ){  // This works in IE and FF too
                o[ rules[j].style.fontFamily ] = rules[j].style.src;
            };
        }
    }
    return o;
}

Upvotes: 1

Paul S.
Paul S.

Reputation: 66364

Find all css-defined fonts, demo here (console).

function getFonts (obj) {
    var o = obj || {},
        sheet = document.styleSheets,
        rule = null,
        i = sheet.length, j;
    while( 0 <= --i ){
        rule = sheet[i].rules || sheet[i].cssRules || [];
        j = rule.length;
        while( 0 <= --j ){
            if( rule[j].constructor.name === 'CSSFontFaceRule' ){ // rule[j].slice(0, 10).toLowerCase() === '@font-face'
                o[ rule[j].style.fontFamily ] = rule[j].style.src;
            };
        }
    }
    return o;
}

Upvotes: 4

Related Questions