0

我收到DOMException: Failed to read the 'cssRules' property from 'CSSStyleSheet': Cannot access rules。任何建议我该如何解决。

示例代码

function copyStyles(source, target) {
  Array.from(source.styleSheets).forEach(styleSheet => {
    let rules
    try {
      rules = styleSheet.cssRules
    } catch (err) {
      console.error(err)
    }
    if (rules) {
      const newStyleEl = source.createElement('style')

      Array.from(styleSheet.cssRules).forEach(cssRule => {
        .......
        
      })
      target.head.appendChild(newStyleEl)
    } else if (styleSheet.href) {
      ..........
    }
  })
}
4

2 回答 2

1

我建议您避免调用可能通过 CSP 保护的 cssRules,而只需添加一个新样式表,其中包含您想要覆盖现有规则的任何规则。

像这样...

var S=document.createElement('style');

S.innerHTML='#Menu{background:red;} body{overflow:auto;}';

Frame_ID.contentWindow.document.body.appendChild(S);
于 2021-05-10T16:18:47.500 回答
1

根据 CORS 安全策略,您不能通过 javascript 访问从第三方域加载的资源的内容。这也适用于 CSS 文件(尽管尚未在所有浏览器中实现)。

因此,如果其中一个source.styleSheets是第三方 CSS 文件,那么您在cssRules尝试rules访问stylesheet

顺便说一句,作为您正在尝试的解决方案,而不是在 else 部分创建链接标签,而是获取(通过 xhr 或fetchAPI)stylesheet.href,您将在 JS 中将响应作为文本附加到样式标签中DOM。

例子

fetch(stylesheet.href)
  .then(response => response.text())
  .then(response => {
      const st = document.createElement('style');
      st.textContent = response;
      document.body.append(st);
  });
于 2021-05-10T16:46:44.890 回答