簡體   English   中英

安全錯誤操作在firefox document.stylesheets中是不安全的

[英]security error the operation is insecure in firefox document.stylesheets

以下代碼在帶有continue的行的Firefox控制台中引發錯誤。

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);
            }
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM