Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
106
rated 0 times [  112] [ 6]  / answers: 1 / hits: 89159  / 11 Years ago, tue, march 19, 2013, 12:00:00

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.


More From » css

 Answers
96

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.


[#79485] Monday, March 18, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
marvinm

Total Points: 406
Total Questions: 104
Total Answers: 121

Location: Iceland
Member since Tue, Jan 25, 2022
2 Years ago
;