gpt4 book ai didi

javascript - 未捕获的 DOMException : Failed to read the 'rules' property from 'CSSStyleSheet'

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:06:46 27 4
gpt4 key购买 nike

在 Code.org 的 App Lab 编辑器中,我们最近开始在 Chrome 64 中看到这个错误:

Uncaught DOMException: Failed to read the 'rules' property from 'CSSStyleSheet'

错误是在这个旨在检测浏览器是否正在使用 CSS 媒体查询的函数中抛出的,在包含 styleSheets[i].cssRules 的行上。

/**
* IE9 throws an exception when trying to access the media field of a stylesheet
*/
export function browserSupportsCssMedia() {
var styleSheets = document.styleSheets;
for (var i = 0; i < styleSheets.length; i++) {
var rules = styleSheets[i].cssRules || styleSheets[i].rules;
try {
if (rules.length > 0) {
// see if we can access media
rules[0].media;
}
} catch (e) {
return false;
}
}
return true;
}

该问题已在 Windows、OSX、Ubuntu 和 ChromeOS 上出现;在 Chrome 版本 64.0.3282.167 和 64.0.3282.186 上。但是,我们也发现这个问题没有发生在完全相同的 Chrome 版本和平台上——而且我们似乎无法在隐身窗口中重现该问题。

此错误的根本原因是什么?

最佳答案

这是一个很好的故事,也是网络开发人员的一个新“难题”,所以我不得不分享:

Chrome 64.0.3282.0(2018 年 1 月发布,full change list)对样式表的安全规则进行了更改。我很恼火,因为我在任何比完整提交列表更详细的变更日志中找不到此更改。

提交 a4ebe08在 Chromium 中描述:

Update behavior of CSSStyleSheet to match spec for Security origin

Spec is here: https://www.w3.org/TR/cssom-1/#the-cssstylesheet-interface

Updated: the following methods now throw a SecurityError if the style sheet is not accessible:

  • cssRules() / rules()
  • insertRule()
  • deleteRule()

此提交修复了错误 Security: Inconsistent CORS implementation regarding CSS and the link element.链接的 W3C 规范详细描述了在何处使用 CSS 对象模型需要同源访问。

综上所述,为什么这个问题会出现在 App Lab 中?我们不应该遇到任何 CORS 问题,因为我们只从我们自己的来源加载样式表:

Chrome network tab showing all CSS requested from the affected page

最后的线索是我们无法在私有(private)选项卡中重现此问题。我们开始查看 Chrome 扩展并意识到一些受影响的用户有 Loom Video Recorder启用扩展,似乎将自己的 CSS 注入(inject)页面。由于我们的(原始)函数正在遍历所有 加载的样式表,它试图访问由扩展注入(inject)的样式表,从而导致 CORS 错误。

也就是说,围绕 Chrome 中的这一变化仍然存在一些悬而未决的问题和争论:

  • This comment在最初的安全漏洞上提示说,现在检测样式表无法从 JavaScript 访问的唯一方法是使用 try/catch
  • 1 月 23 日发现的 Chromium 错误 (document.styleSheets.cssRules is null even with Access-Control-Allow-Origin: *) 表明新安全规则可能存在实现问题,破坏了某些变通办法。
  • 正在实现的规范看起来相当稳定,但它仍处于“工作草案”状态,所以谁知道它会落在哪里以及其他浏览器将实现什么。

To fix our problem, we just tore out the entire function.我们不再支持 IE9,而且我们知道我们支持的所有浏览器都能正确处理媒体查询。

相关(但不完全重复)的问题:

关于javascript - 未捕获的 DOMException : Failed to read the 'rules' property from 'CSSStyleSheet' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49161159/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com