【发布时间】:2018-05-02 13:37:59
【问题描述】:
我正在编写一个 chrome 扩展,它需要遍历页面中的所有样式表并修改某些样式。
我像这样迭代/修改样式:
const iterate = (doc, f) => {
for (const styleSheet of doc.styleSheets) {
const rules = styleSheet.rules || styleSheet.cssRules;
if (!rules) continue;
for (const cssRule of rules) {
if (!cssRule.style) continue;
const selector = cssRule.selectorText, style = cssRule.style;
if (!selector || !style.cssText) continue;
f(style);
}
}
}
document.addEventListener("DOMContentLoaded", e => {
setTimeout(() => {
iterate(document, style => {
if (style.getPropertyValue('background-color')) style.setProperty('background-color', 'yellow');
});
}, 1000);
});
div {
background-color: red;
}
<div>hello</div>
我遇到的问题是似乎没有包含外部 css。
例如,如果我将扩展程序注入到 stackoverflow.com 中,它具有:
<link rel="stylesheet" type="text/css" href="https://cdn.sstatic.net/Sites/stackoverflow/all.css?v=cfd0b49a38a7">
那么来自 all.css 的样式不会被迭代。
如何迭代/修改外部样式?
注意 1 - 我尝试手动获取这些链接 rel 并将它们放入内部样式标签中,但这会破坏这些文件中的任何相对 URL(即 background-image: url('path/image.jpg') )
注意 2 - 我的清单有 "permissions": [ "http://*/*", "https://*/*" ]
注意 3 - 因为这是一个 Chrome 扩展程序,所以我对 Chrome 唯一的解决方案很满意
【问题讨论】:
-
您是否尝试过使用来自this answer 的函数
loadCSSCors? -
FWIW 您可以使用轻量级 css 解析器或直接替换文本...
-
您可以使用
loadCSSCors函数+some regular expression将外部CSS文件中的相对路径替换为绝对路径。 -
要修改外部样式吗?为什么您不使用相同的规则创建自己的样式并覆盖外部?
-
由于 CORS,我相信解决这个问题的唯一方法是使用中间人服务器来获取样式表的内容。
标签: javascript css google-chrome-extension