当我尝试访问外部域上托管的某些 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);
});
});
除了将所有 CSS 文件移至同一域之外,还有其他方法可以解决此问题吗?
解决此问题的唯一真正解决方案是首先使用 CORS 加载 CSS。通过使用 CORSXMLHttpRequest
从外部域加载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();
}
这样,浏览器将把 CSS 文件解释为来自与主页响应相同的源域,现在您将可以访问样式表的 cssRules 属性。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)