I encountered a roadblock while working on a tool.
My task involves accessing the stylesheet object of a website and specifically retrieving the "CSSFontFaceRule". I managed to accomplish this, but the output in my returned object is a lengthy string. I aim to break down the string into an object format. I have also prepared a fiddle for reference: http://jsfiddle.net/9eoytc6v/1/
This represents my current situation:
@font-face {font-family: "Test-Book";
src:
url("https://fontserver.xyz/test.eot?#iefix") format("embedded-opentype"),
url("https://fontserver.xyz/test.woff2") format("woff2"),
url("https://fontserver.xyz/test.woff") format("woff"),
url("https://fontserver.xyz/test.ttf") format("truetype"),
url("https://fontserver.xyz/test.svg#Test-Book") format("svg");
}
let fonts = {};
function getFontPairs(obj) {
let object = obj || {},
stylesheet = document.styleSheets,
rule = null,
length = stylesheet.length,
j;
while (0 <= --length) {
rule = stylesheet[length].rules || stylesheet[length].cssRules || [];
j = rule.length;
while (0 <= --j) {
if (rule[j].constructor.name === "CSSFontFaceRule") {
let sourcesString = rule[j].style.src;
let re = /\s*(?:,|$)\s*/;
let sources = sourcesString.split(re);
let final = [];
sources.forEach(function(element){
let reg = /[ ,]+/;
let srcArray = element.split(reg);
srcArray = srcArray.reverse();
final.push(srcArray);
});
object[rule[j].style.fontFamily] = final;
}
}
}
return object;
}
getFontPairs(fonts);
console.log(fonts);
I attempted to use arrays but the outcome is somewhat disorganized: Current array solution
My goal is to achieve a structure similar to this: Expected object solution
As I am not proficient with RegEx at the moment, I want to remove the url("")
and the format("")
as well.
Any assistance provided would be greatly appreciated. Perhaps someone can offer a more efficient version of my code.