Skip to content
Advertisement

Inject CSS stylesheet as string using Javascript

I’m developing a Chrome extension, and I’d like users to be able to add their own CSS styles to change the appearance of the extension’s pages (not web pages). I’ve looked into using document.stylesheets, but it seems like it wants the rules to be split up, and won’t let you inject a complete stylesheet. Is there a solution that would let me use a string to create a new stylesheet on a page?

I’m currently not using jQuery or similar, so pure Javascript solutions would be preferable.

Advertisement

Answer

There are a couple of ways this could be done, but the simplest approach is to create a <style> element, set its textContent property, and append to the page’s <head>.

/**
 * Utility function to add CSS in multiple passes.
 * @param {string} styleString
 */
function addStyle(styleString) {
  const style = document.createElement('style');
  style.textContent = styleString;
  document.head.append(style);
}

addStyle(`
  body {
    color: red;
  }
`);

addStyle(`
  body {
    background: silver;
  }
`);

If you want, you could change this slightly so the CSS is replaced when addStyle() is called instead of appending it.

/**
 * Utility function to add replaceable CSS.
 * @param {string} styleString
 */
const addStyle = (() => {
  const style = document.createElement('style');
  document.head.append(style);
  return (styleString) => style.textContent = styleString;
})();

addStyle(`
  body {
    color: red;
  }
`);

addStyle(`
  body {
    background: silver;
  }
`);

IE edit: Be aware that IE9 and below only allows up to 32 stylesheets, so watch out when using the first snippet. The number was increased to 4095 in IE10.

2020 edit: This question is very old but I still get occasional notifications about it so I’ve updated the code to be slightly more modern and replaced .innerHTML with .textContent. This particular instance is safe, but avoiding innerHTML where possible is a good practice since it can be an XSS attack vector.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement