2014-02-08 41 views
13

以下代碼在繼續的行中的Firefox控制檯中引發錯誤。安全錯誤操作在Firefox中是不安全的.stylesheets

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; 
} 
+0

[X] SecurityError:操作不安全。 \t if(!sheet.cssRules){continue; } – jchwebdev

+0

這種情況如何不安全?你在傳遞一個CrossSite樣式表嗎?氣味Buggy,我會與Firefox文件。 – jeremyjjbrown

+0

這是一個WordPress的網站,所以,是的,一些樣式表將會來自其他領域 - 例如Google。我顯然不夠先進,無法理解爲什麼這是上述代碼中的問題。 – jchwebdev

回答

16

要嘗試訪問cssRules屬性時規避的SecurityError在Firefox中,你必須使用一個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 
    } 
} 
+1

是啊,但那麼你如何修改風格? – Michael

0

我有與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); 
      } 
     } 
    } 
} 
+0

我需要*修改*樣式 – Michael