Accessing cross-domain style sheet with .cssRules
The only real solution to this problem is to CORS load your CSS in the first place. By using a CORS XMLHttpRequest
to load the CSS from an external domain, and then injecting the responseText (actually responseCSS in this case) into the page via something like:
function loadCSSCors(stylesheet_uri) {
var _xhr = global.XMLHttpRequest;
var has_cred = false;
try {has_cred = _xhr && ('withCredentials' in (new _xhr()));} catch(e) {}
if (!has_cred) {
console.error('CORS not supported');
return;
}
var xhr = new _xhr();
xhr.open('GET', stylesheet_uri);
xhr.onload = function() {
xhr.onload = xhr.onerror = null;
if (xhr.status < 200 || xhr.status >= 300) {
console.error('style failed to load: ' + stylesheet_uri);
} else {
var style_tag = document.createElement('style');
style_tag.appendChild(document.createTextNode(xhr.responseText));
document.head.appendChild(style_tag);
}
};
xhr.onerror = function() {
xhr.onload = xhr.onerror = null;
console.error('XHR CORS CSS fail:' + styleURI);
};
xhr.send();
}
This way the CSS files will be interpreted by the browser as coming from the same origin domain as the main page response and now you will have access to the cssRules properties of your stylesheets.
As of 2013, you can set the "crossorigin" attribute on the <link>
-Element to signal the browser that this CSS is trusted (Mozilla, W3). For this to work, the Server hosting the CSS has to set the Access-Control-Allow-Origin: *
header though.
After that, you can access its rules via Javascript.