使用 Javascript 将 CSS 样式表作为字符串注入 [英] Inject CSS stylesheet as string using Javascript
问题描述
我正在开发 Chrome 扩展程序,我希望用户能够添加自己的 CSS 样式来更改扩展程序页面(而非网页)的外观.我已经研究过使用 document.stylesheets
,但它似乎想要拆分规则,并且不会让您注入完整的样式表.有没有一种解决方案可以让我使用字符串在页面上创建新的样式表?
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?
我目前没有使用 jQuery 或类似工具,因此最好使用纯 Javascript 解决方案.
I'm currently not using jQuery or similar, so pure Javascript solutions would be preferable.
推荐答案
有几种方法可以做到这一点,但最简单的方法是创建一个 元素,设置它的 textContent 属性,并附加到页面的
.
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;
}
`);
如果需要,您可以稍微更改此设置,以便在调用 addStyle()
时替换 CSS,而不是附加它.
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 请注意,IE9 及以下仅允许 最多 32 个样式表,所以在使用第一个片段时要小心.在 IE10 中该数量增加到 4095.
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 这个问题很老了,但我仍然偶尔会收到关于它的通知,所以我更新了代码,使其更现代,并替换了 .innerHTML
和 .textContent
.这个特定的实例是安全的,但尽可能避免 innerHTML
是一个很好的做法,因为它可能成为 XSS 攻击媒介.
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.
这篇关于使用 Javascript 将 CSS 样式表作为字符串注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!