【问题标题】:Javascript: DOMException: Failed to read the 'cssRules' property from 'CSSStyleSheet': Cannot access rulesJavascript:DOMException:无法从“CSSStyleSheet”读取“cssRules”属性:无法访问规则
【发布时间】:2021-05-11 01:05:03
【问题描述】:

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

【问题讨论】:

    标签: javascript reactjs cross-domain domexception


    【解决方案1】:

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

    像这样……

    var S=document.createElement('style');
    
    S.innerHTML='#Menu{background:red;} body{overflow:auto;}';
    
    Frame_ID.contentWindow.document.body.appendChild(S);
    

    【讨论】:

    • WebUser 非常感谢您的时间和建议,但在我的情况下,这是我需要作为一个新窗口来回报的。
    • 在这种情况下,获取所有样式表的集合,然后对它们做任何你需要的事情。
    【解决方案2】:

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

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

    顺便说一句,作为您正在尝试的解决方案,而不是在 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);
      });
    

    【讨论】:

    • 感谢您的回复...您介意如果可能的话请更新答案。
    • 这个fetch(stylesheet.href)会在else if里面吗?
    • @Tammy 是的,它应该是else if (styleSheet.href)的一部分
    • 但我在try catch 上遇到错误。
    • 是的,错误将出现在 try catch 中(或者您在第三方 css 样式表对象上尝试 .cssRule 的任何地方。)这就是存在 if(rules) 块的原因。因此,每次在 try 语句中出现错误时,您的 rules 变量都将是未定义的。所以它会转到你可以通过 xhr 获取 css 并使用响应做任何你想做的事情的地方。
    猜你喜欢
    • 1970-01-01
    • 2019-03-20
    • 1970-01-01
    • 2018-08-16
    • 2018-08-11
    • 1970-01-01
    • 2019-07-14
    • 2023-03-20
    • 1970-01-01
    相关资源
    最近更新 更多