Javascript:DOMException:无法从“CSSStyleSheet”读取“cssRules”属性:无法访问规则

问题描述

我收到 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) {
      ..........
    }
  })
}

解决方法

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

像这样...

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

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

Frame_ID.contentWindow.document.body.appendChild(S);
,

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

因此,如果 source.styleSheets 之一是第三方 CSS 文件,那么您将在尝试访问 cssRulesrulesstylesheet 属性时收到此错误}

顺便说一下,作为您正在尝试的解决方案,而不是在 else 部分创建链接标签,获取(通过 xhr 或 fetch API)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);
  });

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...