Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

External CSS styles cant be accessed in Google Chrome

So i have the following code

<html>
<head>
    <link href="style.css" rel="stylesheet" type="text/css" />

    <script type="text/javascript">
        document.styleSheets[0].cssRules[0].style.color="blue";
    </script>
</head>
//etc.

So basically this code works in IE and Mozilla, but not in Chrome. Actually, when you run document.styleSheets[0].cssRules it returns an CSSRulesList Object(in IE and Mozilla), but in Chrome it returns null. Btw, for embedded styles this object seems to work even in Chrome.

So is this feature actually not available in Chrome? If so, is there a Chrome alternative that enables you to work with external style sheets/files using Javascript?

like image 202
user3398216 Avatar asked Jun 29 '14 01:06

user3398216


People also ask

Why does my CSS not work in Chrome?

Make sure that your CSS and HTM/HTML files use the same encoding ! If your HTM/HTML files are encoded as UNICODE, your stylesheet has to be as well. IE and Edge are not fussy : stylesheets are rendered regardless of the encodings. But Chrome is totally intolerant of unmatched encodings.

Why is my external CSS not working?

Make sure that you add the rel attribute to the link tag When you add an external CSS file to your HTML document, you need to add the rel="stylesheet" attribute to the <link> tag to make it work. If you omit the rel attribute from the <link> tag then the style won't be applied to the page.

How do I access external CSS?

CSS can be added to HTML documents in 3 ways: Inline - by using the style attribute inside HTML elements. Internal - by using a <style> element in the <head> section. External - by using a <link> element to link to an external CSS file.


1 Answers

The alternative

document.styleSheets[0].rules[0].style.color = "blue";

This snippet could be helpful to see which collection is supported. It is recommended to use the cssRules collection first and if it is not supported, then use the rules collection.

if (document.styleSheets[0].cssRules)
    document.styleSheets[0].cssRules[0].style.color = "blue";
else if (document.styleSheets[0].rules)
    document.styleSheets[0].rules[0].style.color = "blue";

EDIT

The snippet below works as expected on IE8, IE11, Firefox, Chrome, Safari and Opera; on my local and production server; it also works on jsbin; but it doesn't work on jsfiddle - on any of the above browser!

<!DOCTYPE>
<html>
<head>
<style type="text/css">
    .panel { 
        background-color: #00ff00; 
        color: #ffffff; 
        width: 100px; 
        height: 100px; 
        font-size: 30px;
    }
</style>
<script type="text/javascript">
window.onload = function(){
    document.getElementById('button').onclick = function() {
        if (document.styleSheets[0].cssRules)
            document.styleSheets[0].cssRules[0].style.color = "black"; 
        else if (document.styleSheets[0].rules)
            document.styleSheets[0].rules[0].style.color = "black";
    };
};
</script>
</head>
<body>
    <div class="panel"><b>Text</b></div>
    <input type="button" name="button" id="button" value="Change Color" />
</body>
</html>

If I change the style section to this

<link rel="stylesheet" type="text/css" href="http://external-server/styles.css" />

the snippet above works only on IE11. So, it seems to be a cross-domain policy issue since Firefox is saying The Same Origin Policy disallows reading the remote resource at http://external-server/styles.css. This can be fixed by moving the resource to the same domain or enabling CORS.

Maybe the following snippet could solve the issue

<style type="text/css">
    @import url("http://external-domain/styles.css");
</style> 

Well, the @import tip failed! But let's check the headers received from the external server

Remote Address: x.x.x.x:x
Request URL: http://www.external-domain.com/styles.css
Request Method: GET
Status Code: 200 OK
+[Request Headers] 10
-[Response Headers] 11
  Accept-Ranges: bytes
  Connection: Keep-Alive
  Content-Encoding: gzip
  Content-Length: 105
  Content-Type: text/css
  ...

As we can see, we have the styles but we can't access or change them. Chrome and Opera are saying

`Uncaught TypeError: Cannot set property 'color' of undefined`;

Firefox is saying the same but in more details

`TypeError: document.styleSheets[0].cssRules[0].style is undefined` 

and finally, even IE11 has the same opinion :)

`SCRIPT5007: Unable to set property 'color' of undefined or null reference. 
File: css.html, Line: 30, Column: 4`   

Well, at this moment there's one more thing to consider - a CORS request?! CORS is supported on IE 8+, Firefox 3.5+, Chrome 3+, Opera 12+, Safari 4+ ...

Access CSS hosted on external domain using CORS

<!DOCTYPE>
<html>
<head>
<meta charset="utf-8">
<script type="text/javascript">
// Access CSS hosted on external domain using CORS
// http://stackoverflow.com/users/1310701/hex494d49
//
window.onload = function(){
    var xhr = CORSRequest("GET", "http://external-domain/styles.css");
    if (!xhr){ // if CORS isn't supported
        alert("Still using Lynx?");
        return;
    }
    xhr.onload = function() {
        var response = xhr.responseText;
        appendCSS(response);
    }
    xhr.onerror = function() {
        alert('Something went wrong!');
    };
    xhr.send();

    document.getElementById('button').onclick = function() {
        if (document.styleSheets[0].cssRules)
            document.styleSheets[0].cssRules[0].style.color = "black"; 
        else if (document.styleSheets[0].rules)
            document.styleSheets[0].rules[0].style.color = "black";
    };
};

var appendCSS = function(css){
    var s = document.createElement('STYLE');
    s.setAttribute('type', 'text/css');
    if(s.styleSheet)  // IE
        s.styleSheet.cssText = css;
    else  // the rest of the world
        s.appendChild(document.createTextNode(css));
    document.getElementsByTagName('HEAD')[0].appendChild(s);
};

var CORSRequest = function(method, url){
    var xhr = new XMLHttpRequest();
    if("withCredentials" in xhr){  // Chrome, Firefox, Opera, Safari
        xhr.open(method, url, true);
    }else if(typeof XDomainRequest != "undefined"){  // IE
        xhr = new XDomainRequest();
        xhr.open(method, url);
    }else{ // CORS isn't supported
        xhr = null;
    }
    return xhr;
};

</script>
</head>
<body>
    <div class="panel"><b>Text</b></div>
    <input type="button" name="button" id="button" value="Change Color" />
</body>
</html>

That's it, it works! Just tested on IE8, IE11, Firefox, Chrome, Opera and Safari. But... only if the Access-Control-Allow-Origin is enabled on the web-server, otherwise you'll get an error like this

XMLHttpRequest cannot load http://external-domain/styles.css. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.

On my server it wasn't enabled so I had to do it myself. This may be a problem if one is on shared hosting.

Off-topic: How to enable Access-Control-Allow-Origin on Apache

First, enable the Apache Headers module

ln -s /etc/apache2/mods-available/headers.load /etc/apache2/mods-enabled/headers.load

Restart Apache

/etc/init.d/apache2 restart

Under the Directory section of your Apache config file add these lines

Header add Access-Control-Allow-Origin "*"
Header add Access-Control-Allow-Headers "origin, x-requested-with, content-type"
Header add Access-Control-Allow-Methods "PUT, GET, POST, DELETE, OPTIONS"

or add them in a .htaccess file. The last two may be omitted. If you want to limit access to only someone, replace the "*" from the previous line to, let's say, "www.my-kitchen.com". Another restart of web-server and that's it.

like image 105
hex494D49 Avatar answered Oct 27 '22 12:10

hex494D49