javascript - 安全错误 firefox document.stylesheets 中的操作不安全

标签 javascript security error-handling stylesheet

以下代码在 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
  }
}

关于javascript - 安全错误 firefox document.stylesheets 中的操作不安全,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21642277/

相关文章:

php - 为站点抓取入口域

java - 如何仅在 Spring Security 上对某些 URL 强制使用 https?

android - 如何在 android 系统/root 中运行应用程序

javascript - 加载 twitter 推文 410 错误

javascript - 以 4 倍速度运行 Javascript 时钟

javascript - 如何使用 XMLHttpRequest 从 json 生成变量?

ruby-on-rails - 当在HTTP header 而不是cookie中找到加密值时,如何解密 `.signed`?

javascript - 每个模块只有一个默认导出允许使用 Navbar 在 React Native 上出错

python - InvalidArgumentError : input depth must be evenly divisible by filter depth: 4 vs 3

javascript - React-Native:虽然前面有声明,但 undefined 不是对象