Accessing cross-domain style sheet with .cssRules

2019-01-09 05:20发布

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?

7条回答
三岁会撩人
2楼-- · 2019-01-09 06:16

I had a similar issue under firefox and chrome. I've solved it in a harsh way by adding to my domain a css file which included the external domain css, like this:

<style type="text/css">
@import url("https://externaldomain.com/includes/styles/cookie-btn.css");
</style>

It's fast but dirty. It's recommended to keep all css files in your domain.

查看更多
登录 后发表回答