Skip to content

Instantly share code, notes, and snippets.

@bramus
Last active September 20, 2023 22:16
Show Gist options
  • Save bramus/b7b19751b8cb684d06b94136d715933e to your computer and use it in GitHub Desktop.
Save bramus/b7b19751b8cb684d06b94136d715933e to your computer and use it in GitHub Desktop.
Get all Cascade Layers on a page
const extractLayersFromCssRules = (cssRules) => {
if (!cssRules || !cssRules.length) return [];
return [...cssRules].filter((cssRule) => {
return (cssRule instanceof CSSStyleRule) || (cssRule instanceof CSSLayerBlockRule);
})
.flatMap((cssRule) => {
if (cssRule instanceof CSSLayerBlockRule) {
return [cssRule.name];
} else {
return extractLayersFromCssRules(cssRule.cssRules);
}
});
}
const layers = [...document.styleSheets].flatMap((styleSheet) => {
try {
const rules = styleSheet.cssRules;
return extractLayersFromCssRules(rules);
} catch (e) {
console.warn(`Could not read the cssRules from the stylesheet “${styleSheet.href}”. Try setting \`crossorigin="anonymous"\` on it.`);
return [];
}
});
const uniques = [...new Set(layers)];
console.log(uniques);
@AndrewKGuan
Copy link

Looks like CSS fonts will cause an exception:
Uncaught DOMException: Failed to read the 'cssRules' property from 'CSSStyleSheet': Cannot access rules
at :16:47
at Array.flatMap ()
at :14:42

I ran into this one with 'https://fonts.googleapis.com/css?family=Montserrat:500,600,800|Open+Sans:400,600,700&display=swap'
Screenshot 2023-08-10 at 2 32 10 PM

@bramus
Copy link
Author

bramus commented Aug 11, 2023

@AndrewKGuan The problem is that that stylesheet is an external one that cannot be read. Updated the gist to include a safeguard against this. Note that the file is skipped in that case.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment