security error the operation is insecure in firefox document.stylesheets

前端 未结 2 1428
感动是毒
感动是毒 2020-12-10 01:55

The following code throws an error in the Firefox Console at the line with the continue.

SecurityError: The operation is insecure.
if( !sheet.cssRules ) { c         


        
相关标签:
2条回答
  • 2020-12-10 02:38

    To circumvent the SecurityError in Firefox when attempting to access the cssRules attribute, you must use a try/catch statement. The following should work:

    // 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
      }
    }
    
    0 讨论(0)
  • 2020-12-10 02:50

    I had the same issue with Firefox. Try this instead.

    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 讨论(0)
提交回复
热议问题