从chrome扩展更改外部CSS

kof*_*fus 9 javascript css google-chrome-extension

我正在编写一个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);
});
Run Code Online (Sandbox Code Playgroud)
div {
  background-color: red;
}
Run Code Online (Sandbox Code Playgroud)
<div>hello</div>
Run Code Online (Sandbox Code Playgroud)

我遇到的问题是外部css似乎没有被包括在内.

例如,如果我将我的扩展注入stackoverflow.com,它具有:

<link rel="stylesheet" type="text/css" href="https://cdn.sstatic.net/Sites/stackoverflow/all.css?v=cfd0b49a38a7">
Run Code Online (Sandbox Code Playgroud)

那么all.css中的样式不会被迭代.

如何迭代/修改外部样式?

注1 - 我试图手动获取这些链接rel并将它们放入内部样式标记但会破坏这些文件中的任何相对URL(即background-image: url('path/image.jpg'))

注2 - 我的清单有 "permissions": [ "http://*/*", "https://*/*" ]

注意3 - 因为这是针对Chrome扩展程序的,我对仅支持Chrome的解决方案感到满意

N-a*_*ate 0

这可能是您的示例代码中的错误,但很明显,它不太可能在DOMContentLoaded 事件 + 1 秒之前注入并获取样式表。尝试将 setTimeout 等待更改为20 秒,看看会发生什么。

如果这解决了您的问题,那么下一步就是创建一个更好的解决方案,等到样式表显示后再进行迭代。