Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

document.styleSheets[x].cssRules are null

Tags:

css

stylesheet

When I inspect a website,
I see the cssRules from document.styleSheets[x].cssRules

enter image description here

However, with this website stackoverflow.com, when I inspect with Chrome browser, I see document.styleSheets, but cssRules is null.

enter image description here

How come this is possible?

like image 357
allenhwkim Avatar asked Sep 11 '26 12:09

allenhwkim


2 Answers

That's because the style sheets are coming from a different domain. Some browsers (such as Chrome) implement strict cross-domain policies by throwing security errors or setting the cssRules and ownerRule to null when it comes from a different domain...in your case the style sheets come from a CDN

MDN quotes the following in the CSSStyleSheet documentation...

In some browsers, if a stylesheet is loaded from a different domain, calling cssRules results in SecurityError.

https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleSheet

like image 77
Leo Avatar answered Sep 13 '26 06:09

Leo


To try bypass this problem, you can add crossorigin="anonymous" in the link tag to prevent the error.

More info here:

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

This will create a potencial cors request but the server must respond with Access-Control-Allow-Origin: * or Access-Control-Allow-Origin: <authorized-domain>.

You can check here to see how to add CORS support to your server.

For more information about CORS you can read this and this.

like image 32
Paulo Belo Avatar answered Sep 13 '26 04:09

Paulo Belo