2

I am trying to get all CSS rules by using JavaScript. On some page I sucess, on some I don't success.

For example, here in StackOverflow, I am using:

console.log(
document.styleSheets[1].href,'rules',
document.styleSheets[1].cssRules,'Should be css rules, and not null'
)

This is what I get:

http://cdn.sstatic.net/stackoverflow/all.css?v=f7d3e9ff74be rules null Should be css rules, and not null

For some other website it's works well, but sometimes not.

For example in github.com this is what I get:

https://assets-cdn.github.com/assets/github2/index-87247f16e6450ef54cb0eda3f8f1484e33a3f18c7a7d3df1f76f67cba36a8d6d.css CSSRuleList {0: CSSStyleRule, 1: CSSStyleRule, 2: CSSStyleRule, 3: CSSStyleRule, 4: CSSStyleRule, 5: CSSStyleRule, 6: CSSStyleRule, 7: CSSStyleRule, 8: CSSStyleRule, 9: CSSStyleRule, 10: CSSStyleRule, 11: CSSStyleRule, 12: CSSStyleRule, 13: CSSStyleRule, 14: CSSStyleRule, 15: CSSStyleRule, 16: CSSStyleRule, 17: CSSStyleRule, 18: CSSStyleRule, 19: CSSStyleRule, 20: CSSStyleRule, 21: CSSStyleRule, 22: 

What Can I do?

Console example on stackoverflow

  1. I thought maybe it is because content-type. but no. It is always text/css
  2. I thought maybe it because CORS issue, but I didn't see that this is the problem.
Aminadav Glickshtein
  • 23,232
  • 12
  • 77
  • 117
  • 1
    Are you sure it's not a CORS issue? See http://stackoverflow.com/questions/5678040/cssrules-rules-are-null-in-chrome – Matt Browne Aug 03 '15 at 20:51
  • 1
    And: http://stackoverflow.com/a/18471848/560114 – Matt Browne Aug 03 '15 at 20:52
  • It is not CORS issue, after reading those questions, I understand that it is impossible from other domains (even if allow access-control) – Aminadav Glickshtein Aug 03 '15 at 20:56
  • Why don't you think it's CORS? `cdn.sstatic.net` is not the same domain as `stackoverflow.com`, so you can't access the styles. – Barmar Aug 03 '15 at 20:59
  • It's very much not CORS. What output are you expecting? Are you expecting `null` to not be null? The element that you're trying to get the `href` of doesn't have an `href`, so it IS `null`. – MattDiamant Aug 03 '15 at 21:03
  • I think we need a better example...the stackoverflow styles for `styleSheets[1]` aren't available because they're from a different domain. Can you give an example of this happening with stylesheets on the same domain, on a publicly accessible site (so we can test it)? – Matt Browne Aug 03 '15 at 21:31

1 Answers1

1

document.styleSheets contains<style type="text/css"></style> as well as <link rel="stylesheet" type="text/css" href="style.css"> so you will not get href from the first one. I would check if those styles are not blank as well, in case they have no cssRules.

Alex
  • 26
  • 1