Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cannot access rules in external CSSStyleSheet

I am having trouble figuring out why .cssRules and .rules won't work in my simplistic color generator project.

I have a <link> element to link my external CSS file:

<link href="ColorGenerator.css" type="text/css" rel="stylesheet">

And a <script> element to link my external JS file before the </html> element:

<script src="ColorGenerator.js" type="text/javascript"></script>

I then have this in my CSS file:

* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}

#body {
  background: #E1E1F4;
}

And this on the JS file:

const mySheet = document.styleSheets[0];
const body = document.getElementById("body");

body.onkeydown = function(e) {
  if (e.keyCode == 32) {
    mySheet.rules[0].style.background = "#ffa500";
  }
};

But when I press space(e.keyCode == 32) nothing happens, so then I open the developer tools in Chrome and I get this error message:

Uncaught DOMException: Failed to read the 'rules' property from 'CSSStyleSheet': Cannot access rules at HTMLBodyElement.body.onkeydown

I'm not sure if Chrome just doesn't support it or if I have a failure in my code, eitherway I truly appreciate any help.

like image 830
nico.user Avatar asked Mar 03 '18 19:03

nico.user


1 Answers

As of Chrome 64, new CORS rules are enforced for stylesheets. You'll need to use a local development server to do local testing of functionality that depends on the CSS Object Model. For details, see Cannot access cssRules from local css file in Chrome.

like image 124
Brad Buchanan Avatar answered Oct 24 '22 10:10

Brad Buchanan