因此,我一直读到,您不能访问外部样式表的cssRules,因为它会遇到CORS策略问题。
我决定采取一种不同的方法,但我仍然遇到一些问题。
我的方法:
purposes
link
标记的现有链接和新链接,并添加一个新标记,指向我的CDNdocument.styleSheets
我想弄明白的是,如果我的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
来自Network的结果
发布于 2022-03-02 18:24:32
我最终找到了解决办法..。
感谢这个链接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。
发布于 2022-07-29 17:36:57
对于ReactJS,
error)
crossorigin="anonymous"
(e 111
,它提供跨源的css)。示例:
https://stackoverflow.com/questions/71327187
复制相似问题