In the new Chrome, reading external style sheets using Javascript might break due to CORS.
Does anyone know a way around this, and if nothing, let this be a warning if you use CDN.
https://stackoverflow.com/a/49994161
This was helpful:
https://betterprogramming.pub/how-to-fix-the-failed-to-read-the-cssrules-property-from-cssstylesheet-error-431d84e4a139
Here is a version that filters out remote sheets so you still get your local styles I also used Array.from() to improve readability
var allCSSVars = Array.from(document.styleSheets)
.filter((styleSheet) => {
let isLocal = !styleSheet.href || styleSheet.href.startsWith(window.location.origin)
if (!isLocal) console.warn("Skipping remote style sheet due to cors: ", styleSheet.href);
return isLocal;
})
.map((styleSheet) => Array.from(styleSheet.cssRules))
.flat()
.filter((cssRule) => cssRule.selectorText === ':root')
.map((cssRule) => cssRule.cssText.split('{')[1].split('}')[0].trim().split(';'))
.flat()
.filter((text) => text !== '')
.map((text) => text.split(':'))
.map((parts) => {
return {key: parts[0].trim(), value: parts[1].trim()}
})
console.log("vars: ", allCSSVars)
//another way not sure whitch is best but the top way is looking promising
allCSSVars = [].slice.call(document.styleSheets)
.reduce(function (prev, styleSheet) {
try {
if (styleSheet.cssRules) {
return prev + [].slice.call(styleSheet.cssRules)
.reduce(function (prev, cssRule) {
if (cssRule.selectorText == ':root') {
var css = cssRule.cssText.split('{');
css = css[1].replace('}', '').split(';');
for (var i = 0; i < css.length; i++) {
var prop = css[i].split(':');
if (prop.length == 2 && prop[0].indexOf('--') == 1) {
console.log('Property name: ', prop[0]);
console.log('Property value:', prop[1]);
}
}
}
}, '');
}
} catch (e) {
console.warn("Skiping: ", e)
return [];
}
}, '');
:root {
--bc: #fff;
--bc-primary: #eee;
--bc-secondary: #ddd;
}
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/water.css@2/out/water.css">
This is shows what happens without the try statement, I wasn't able to convert this dense code quickly so used the more traditional version :).
const variables = [].slice.call(document.styleSheets)
.map((styleSheet) => [].slice.call(styleSheet.cssRules))
.flat()
.filter((cssRule) => cssRule.selectorText === ':root')
.map((cssRule) => cssRule.cssText.split('{')[1].split('}')[0].trim().split(';'))
.flat()
.filter((text) => text !== '')
.map((text) => text.split(':'))
.map((parts) => parts[0].trim() + ': ' + parts[1].trim())
;
console.log(variables.join('\n'));
:root {
--foo: #fff;
--bar: #aaa
}
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/water.css@2/out/water.css">