首页 > 解决方案 > sheet.cssRules 在内页上抛出错误,但在主页上工作正常

问题描述

我在我的 Wordpress 网站的自定义 javascript 中使用此功能。

var addRule = (function (sheet) {
    if(!sheet) return;
    return function (selector, styles) {
        console.log(sheet.cssRules)
        if (sheet.insertRule) return sheet.insertRule(selector + " {" + styles + "}", sheet.cssRules.length);
        if (sheet.addRule) return sheet.addRule(selector, styles);
    }
}(document.styleSheets[document.styleSheets.length - 1]));

这里的问题是上述功能在主页上运行良好,但是,

Uncaught DOMException: Failed to read the 'cssRules' property from 'CSSStyleSheet': Cannot access rules在内页上抛出。

这是我网站的链接,

主页 //here you will see no error in console

内页 //here you will see an error in console

根据我的研究,此错误是由跨域资源共享 (CORS) 引起的,但为什么它在主页上起作用?

标签: javascriptcssgoogle-chromedom

解决方案


毫无疑问,问题是由 CORS 引起的。我建议您在执行此操作后console.log(document.styleSheets)查看href元素以检查将哪个样式表传递给您的 addrule() document.styleSheets.length - 1,样式表的 href 应该与您的域相同。


推荐阅读