Skip to content

Instantly share code, notes, and snippets.

@davidgilbertson
Last active December 9, 2019 20:41
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save davidgilbertson/ed3c8bb8569bc64b094b87aa88bed5fa to your computer and use it in GitHub Desktop.
Save davidgilbertson/ed3c8bb8569bc64b094b87aa88bed5fa to your computer and use it in GitHub Desktop.
function copyStyles(sourceDoc, targetDoc) {
Array.from(sourceDoc.styleSheets).forEach(styleSheet => {
if (styleSheet.cssRules) { // for <style> elements
const newStyleEl = sourceDoc.createElement('style');
Array.from(styleSheet.cssRules).forEach(cssRule => {
// write the text of each rule into the body of the style element
newStyleEl.appendChild(sourceDoc.createTextNode(cssRule.cssText));
});
targetDoc.head.appendChild(newStyleEl);
} else if (styleSheet.href) { // for <link> elements loading CSS from a URL
const newLinkEl = sourceDoc.createElement('link');
newLinkEl.rel = 'stylesheet';
newLinkEl.href = styleSheet.href;
targetDoc.head.appendChild(newLinkEl);
}
});
}
@jiayihu
Copy link

jiayihu commented Jul 3, 2018

From Chrome 64 using .cssRules on sheets from other domains will throw, so it's important to first check if the sheet is external, then if the <style> element has any CSS rules.

function copyStyles(sourceDoc, targetDoc) {
  Array.from(sourceDoc.styleSheets).forEach(styleSheet => {
    if (styleSheet.href) {
      // for <link> elements loading CSS from a URL
      ...
    } else if (styleSheet.cssRules && styleSheet.cssRules.length > 0) {
      // for <style> elements
      ...
    }
  });
}

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