I get this error in Firebug when I try to access some CSS files hosted on external domains:
Security error" code: "1000
rules = styleSheets[i].cssRules;
The code I am using is:
$(document).ready(function () {
$("p").live('mousedown', function getCSSRules(element) {
element = $(this);
var styleSheets = document.styleSheets;
var matchedRules = [],
rules, rule;
for (var i = 0; i < styleSheets.length; i++) {
rules = styleSheets[i].cssRules;
for (var j = 0; j < rules.length; j++) {
rule = rules[j];
if (element.is(rule.selectorText)) {
matchedRules.push(rule.selectorText);
}
}
}
alert(matchedRules);
});
});
Is there a way to fix this, beside moving all the CSS files on the same domain?
You may have to write a proxy for that CSS-file.
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 theAccess-Control-Allow-Origin: *
header though.After that, you can access its rules via Javascript.
I wrote a little function that will solve the loading problem cross-browser including FF. The comments on GitHub help explain usage. Full code at https://github.com/srolfe26/getXDomainCSS.
Disclaimer: The code below is jQuery dependent.
Sometimes, if you're pulling CSS from a place that you can't control the CORS settings you cans till get the CSS with an
<link>
tag, the main issue to be solved then becomes knowing when your called-for CSS has been loaded and ready to use. In older IE, you could have anon_load
listener run when the CSS is loaded.Newer browsers seem to require old-fashioned polling to determine when the file is loaded, and have some cross-browser issues in determining when the load is satisfied. See the code below to catch some of those quirks.
If this triggers for you because some of your CSS may come from elsewhere but NOT the bit you are interested in, use a try... catch block like this:
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: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.
If you have control over the domain where the external stylesheet is hosted, it may help to add an appropriate Access-Control-Allow-Origin header.