Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uncaught DOMException: Failed to read the 'cssRules' property

I wonder why does my script work on firefox but not on google chrome

JS:

var _timelineWidth = (Number.parseInt(document.styleSheets[0].cssRules[16].style.width) / 100) * document.body.clientWidth;

CSS:

#timeline {
  position: relative;
  top: 15px;
  left: 12.5%;
  height: 5px;
  background: #aaa;
  border-radius: 2.5px;
  cursor: pointer;
}

here's the error code from chrome

Uncaught DOMException: Failed to read the 'cssRules' property from 'CSSStyleSheet': Cannot access rules

like image 606
Kemal Dwiheldy Avatar asked Apr 24 '18 04:04

Kemal Dwiheldy


2 Answers

In latest Chrome, CORS security rules are applicable for style-sheets also (Similar to Iframe rules).

You can load and render them but, cannot access the content through javascript (If loaded from Cross-Domain ).

If your CSS Stylesheet is from Same domain as of HTML /or included in same HTML file, you will be able to access document.styleSheets[elem].cssRules otherwise it will throw error

Uncaught DOMException: Failed to read the 'cssRules' property from 'CSSStyleSheet': Cannot access rules

Cross Domain Stylesheet

Cross Domain Stylesheet

Same Domain Stylesheet

Same Domain Stylesheet

like image 180
Atul Sharma Avatar answered Nov 15 '22 22:11

Atul Sharma


You can add crossorigin="anonymous" to prevent the error.

<link rel="stylesheet" href="https://..." crossorigin="anonymous">

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 44
Paulo Belo Avatar answered Nov 15 '22 22:11

Paulo Belo