18

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.

Alex
  • 171
  • 2
  • 10
nico.user
  • 483
  • 2
  • 5
  • 15
  • I am not too familiar with `CSSStyleSheet` but the fruitful manual says it has a `cssRules` member, not `rules`. Could that be related? – Renardo Mar 03 '18 at 19:54
  • I tried using both `.cssRules` and `.rules`, but both of them give me the same error – nico.user Mar 03 '18 at 20:03
  • In my Firefox 58 it works with `cssRules`; Chromium says “Failed to read the 'cssRules' property from 'CSSStyleSheet'“”. I do not know why. What browser are you using? – Renardo Mar 03 '18 at 20:19
  • 1
    I think there may be a bug in Chrome 64. I've seen a couple of issues logged on different Github projects that seem to reference the same issue. Good luck. – denmch Mar 03 '18 at 20:49
  • 1
    Are you doing this in a page served from a server (HTTP or HTTPS)? Or in a page served from the file system (file:// URL)? The latter might be broken and it is generally not a recommended way of browsing, as it is broken (for security purposes) in many aspects. – PhistucK Mar 04 '18 at 07:27
  • It's seems not work at all. I'm 64.0.3282.186 – yangsibai Mar 16 '18 at 06:03

2 Answers2

26

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.

Brad Buchanan
  • 1,475
  • 1
  • 15
  • 22
0

I just got hit by the same problem. In my case it was possible to use fetch(the.css) to fix it.

Leo
  • 4,136
  • 6
  • 48
  • 72