Reputation: 509
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
Upvotes: 27
Views: 64504
Reputation: 139
I had the exact same problem, and the answer crossorigin="anonymous"
didn't fix it - because I wanted to run things from the local file system! Chrome's interpretation of CORS for local files are very strict. In this case you can forget about crossorigin="..." attributes, and simply start Chrome with the flag --allow-file-access-from-files
P.S.: No need to install a local testing server, as suggested elsewhere to a despairing front-end developer.
Upvotes: 2
Reputation: 4447
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.
Upvotes: 32
Reputation: 10720
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
Same Domain Stylesheet
Upvotes: 35