Reputation: 339
I am using this function in my Wordpress site's custom 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]));
The problem here is the above function works fine on homepage but,
Throws Uncaught DOMException: Failed to read the 'cssRules' property from 'CSSStyleSheet': Cannot access rules
on inner pages.
Here is the link to my site,
Homepage //here you will see no error in console
Inner Page //here you will see an error in console
as per my research, this error is caused by Cross-Origin Resource Sharing (CORS), but why it is working on Homepage?
Upvotes: 0
Views: 135
Reputation: 1900
No doubt that the problem is caused by CORS. I suggest you to console.log(document.styleSheets)
and see the href
of the element to check which stylesheet is getting passed to your addrule() after doing this document.styleSheets.length - 1
, the stylesheet's href should be same as your domain.
Upvotes: 1
Reputation: 1531
I understand you code is absolutely fine when we compare both pages and also try close console.log with (;) semi colon in your script.
console.log(sheet.cssRules);
Upvotes: 0
Reputation: 41
It's not going to work without you including "../" before the sheet.cssRule. Just go ahead and count the depth of your internal file and add "../" to be exactly equal to that value.
Writing something like "../../../../sheet.cssRule" instead of "sheet.cssRule" should get the problem solved.
Upvotes: 0