Last active
September 20, 2023 22:16
-
-
Save bramus/b7b19751b8cb684d06b94136d715933e to your computer and use it in GitHub Desktop.
Get all Cascade Layers on a page
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@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.