当我尝试访问外部域上托管的一些CSS文件时,我在Firebug中收到此错误:
Security error" code: "1000 rules = styleSheets[i].cssRules;
我使用的代码是:
$(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); }); });
解决方法
这个问题的唯一真正解决方案是CORS首先加载你的CSS。通过使用CORS xmlHTTPRequest从外部域加载CSS,然后将responseText(在这种情况下实际为responseCSS)注入页面,方法如下:
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(); }