我正在编写一个chrome扩展程序,该扩展程序需要迭代其注入(inject)到的页面中的所有样式表并修改某些样式。
我像这样迭代/修改样式:
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。
例如,如果我将扩展名注入(inject)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-我的 list 上有
"permissions": [ "http://*/*", "https://*/*" ]
注意3-这是针对Chrome扩展程序的,我对仅适用于Chrome的解决方案感到满意
最佳答案
这可能是示例代码中的错误,但是很明显,在 DOMContentLoaded事件+ 1秒之前,不太可能注入(inject)和获取样式表。尝试将setTimeout等待时间更改为 20秒,然后看看会发生什么。
如果这解决了您的问题,那么下一步是创建一个更好的解决方案,该解决方案要等到样式表出现后再进行迭代。
关于javascript - 从Chrome扩展程序更改外部CSS,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47373308/