【问题标题】:Cannot Access cssRules for Stylesheet CORS无法访问样式表 CORS 的 cssRules
【发布时间】:2022-03-03 02:36:57
【问题描述】:

所以我一直在读到您无法访问外部样式表的 cssRules,因为它遇到了 CORS 政策问题。

我决定采用不同的方法,但我仍然遇到问题。

我的方法:

  1. 在后端下载css文件并上传到S3 Bucket
  2. 返回现有链接和新链接以进行匹配
  3. 删除现有的link 标签并添加一个指向我的 CDN 的新标签
  4. 访问document.styleSheets
  5. Tadaaaa(但失败了)

我想弄清楚的是,如果我的 CDN 允许从任何来源访问,为什么我仍然会遇到问题?

export default () => {
  const payload = [...document.styleSheets].filter(s => s.href).map(s => s.href);

  axios.post('SOME ENDPOINT', { css: payload }).then(({ status, data: { data: newLinks } }) => {
    if (status === 200) {
      for (const i in newLinks) {
        document.querySelector(`link[href="${newLinks[i].source}"]`).remove()
        const stylesheet = document.createElement('link');
        stylesheet.rel = 'stylesheet';
        stylesheet.href = newLinks[i].downloaded;
        document.getElementsByTagName('head')[0].appendChild(stylesheet);
      }
    }
  }).then(() => {
    let delay = 250
    setTimeout(() => {
      console.log('Stylesheets with Removed Links', [...document.styleSheets]);
    }, delay)
  }).then(() => {
    console.log([...document.styleSheets])
  })
}

Safari 上的错误SecurityError: Not allowed to access cross-origin stylesheet

我看过这个链接Cannot access cssRules from local css file in Chrome 64

网络选项卡的结果

【问题讨论】:

  • 执行document.getElementsByTagName('head')[0].appendChild(stylesheet) 应该会触发对该样式表的请求。该请求在“网络”选项卡中看起来正常吗?
  • @James 是的,这一切看起来都不错。更新了请求的描述

标签: javascript css amazon-s3 cors cdn


【解决方案1】:

我最终找到了解决方案...

感谢来自此链接的 Paulo Belo Uncaught DOMException: Failed to read the 'cssRules' property

stylesheet.crossOrigin = "anonymous" 解决了我的问题,让我可以访问 cssRules。

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

请注意,此修复不适用于引发此错误的现有样式表。

Exception: DOMException: Failed to read the 'cssRules' property from 'CSSStyleSheet': Cannot access rules at CSSStyleSheet.s

此修复仅适用于您自己上传的工作表,或者在我的情况下是来自我的 CDN 的工作表。

【讨论】:

    猜你喜欢
    • 2011-03-13
    • 2019-07-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多