Instantly share code, notes, and snippets.

Embed
What would you like to do?
copy css rules from a document to another one
// at src document
const rules = Array.from(document.styleSheets)
.reduce((sum, sheet) => {
// errors in CORS at some sheets (e.g. qiita)
// like: "Uncaught DOMException: Failed to read the 'cssRules' property from 'CSSStyleSheet': Cannot access rules"
try {
return [...sum, ...Array.from(sheet.cssRules).map(rule => rule.cssText)];
} catch(e) {
// console.log('errored', e);
return sum;
}
}, []);
// at dst document
const newSheet = document.querySelector('head').appendChild(document.createElement('style')).sheet;
rules.forEach(rule => newSheet.insertRule(rule, newSheet.length));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment