安全错误 该操作在 Firefox 文档样式表中不安全



以下代码在 Firefox 控制台中与 continue 的行处抛出错误。

SecurityError: The operation is insecure.
if( !sheet.cssRules ) { continue; }

但是在Chrome和IE 11中没有...有人可以解释一下为什么吗?(以及如何返工以确保其安全。我认为这是一个跨域问题,但我被困在如何正确重新编写代码上。

var bgColor = getStyleRuleValue('background-color', 'bg_selector');
function getStyleRuleValue(style, selector, sheet) {
  var sheets = typeof sheet !== 'undefined' ? [sheet] : document.styleSheets;
  for (var i = 0, l = sheets.length; i < l; i++) {
    var sheet = sheets[i];
    if( !sheet.cssRules ) { continue; }
    for (var j = 0, k = sheet.cssRules.length; j < k; j++) {
      var rule = sheet.cssRules[j];
      if (rule.selectorText && rule.selectorText.split(',').indexOf(selector) !== -1) 
         return rule.style[style];            
     }
   }
  return null;
 }

要在尝试访问 cssRules 属性时规避 Firefox 中的 SecurityError,必须使用 try/catch 语句。以下方法应该有效:

// Example call to process_stylesheet() with StyleSheet object.
process_stylesheet(window.document.styleSheets[0]);
function process_stylesheet(ss) {
  // cssRules respects same-origin policy, as per
  // https://code.google.com/p/chromium/issues/detail?id=49001#c10.
  try {
    // In Chrome, if stylesheet originates from a different domain,
    // ss.cssRules simply won't exist. I believe the same is true for IE, but
    // I haven't tested it.
    //
    // In Firefox, if stylesheet originates from a different domain, trying
    // to access ss.cssRules will throw a SecurityError. Hence, we must use
    // try/catch to detect this condition in Firefox.
    if(!ss.cssRules)
      return;
  } catch(e) {
    // Rethrow exception if it's not a SecurityError. Note that SecurityError
    // exception is specific to Firefox.
    if(e.name !== 'SecurityError')
      throw e;
    return;
  }
  // ss.cssRules is available, so proceed with desired operations.
  for(var i = 0; i < ss.cssRules.length; i++) {
    var rule = ss.cssRules[i];
    // Do something with rule
  }
}

我在使用Firefox时遇到了同样的问题。试试这个。

function getStyle(styleName, className) {
    for (var i=0;i<document.styleSheets.length;i++) {
        var s = document.styleSheets[i];
        var classes = s.rules || s.cssRules
        for(var x=0;x<classes.length;x++) {
            if(classes[x].selectorText==className) {
                return classes[x].style[styleName] ? classes[x].style[styleName] : classes[x].style.getPropertyValue(styleName);
            }
        }
    }
}

最新更新