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);
@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