【问题标题】:Uncaught DOMException: Failed to read the 'cssRules' property未捕获的 DOMException:无法读取“cssRules”属性
【发布时间】:2018-04-24 04:47:08
【问题描述】:

我想知道为什么我的脚本可以在 Firefox 上运行,但不能在 google chrome 上运行

JS:

var _timelineWidth = (Number.parseInt(document.styleSheets[0].cssRules[16].style.width) / 100) * document.body.clientWidth;

CSS:

#timeline {
  position: relative;
  top: 15px;
  left: 12.5%;
  height: 5px;
  background: #aaa;
  border-radius: 2.5px;
  cursor: pointer;
}

这是来自 chrome 的错误代码

未捕获的 DOMException:无法从 'CSSStyleSheet': 无法访问规则

【问题讨论】:

标签: javascript google-chrome


【解决方案1】:

在最新的 Chrome 中,CORS 安全规则也适用于样式表(类似于 Iframe 规则)。

您可以加载和呈现它们,但不能通过 javascript 访问内容(如果从跨域加载)。

如果您的 CSS 样式表来自与 HTML 相同的域/或包含在同一 HTML 文件中,您将能够访问 document.styleSheets[elem].cssRules 否则会抛出错误

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

跨域样式表

同域样式表

【讨论】:

  • 我使用的是外部 CSS,但没有上传到任何地方,为什么它不起作用??
  • 检查 URL.. html 和样式表域必须相同.. 无论是本地主机还是文件系统。
  • 感谢@AtulSharma 的回答,您能否也建议访问内容的方法。
  • @anchal20 您无法从 Chrome 中的外部样式表修改类。不过,您可以将需要修改的类复制到您的主文件中,或者在您的代码中通过 JS 覆盖它们或直接操作 html 元素。
  • 感谢@AtulSharma 的建议。看来这是唯一的解决方案
【解决方案2】:

您可以添加crossorigin="anonymous"以防止错误。

<link rel="stylesheet" href="https://..." crossorigin="anonymous">

更多信息在这里:

https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/crossorigin

这将创建一个potencial cors request,但服务器必须以Access-Control-Allow-Origin: *Access-Control-Allow-Origin: <authorized-domain> 响应。

您可以查看here,了解如何为您的服务器添加 CORS 支持。

有关 CORS 的更多信息,您可以阅读 thisthis

【讨论】:

  • 嗯...这似乎并不实际工作,至少在 Chrome 中
  • @DanielMiller,你可能是对的。虽然它解决了我的问题,但我想它取决于服务器响应标头。我已经更新了我的答案以反映这一点。
  • 我也使用 Chrome,添加 crossorigin="anonymous" 确实解决了我的问题。
  • 这确实有效,但我有一个不同的方法来解决我试图做的事情stackoverflow.com/questions/71327187/…
猜你喜欢
  • 1970-01-01
  • 2018-08-16
  • 2017-07-08
  • 2021-06-09
  • 1970-01-01
  • 1970-01-01
  • 2022-11-20
  • 2022-11-24
  • 2022-12-20
相关资源
最近更新 更多