简体   繁体   English

如何检查document.styleSheets [i]对象中是否存在属性cssRules?

[英]How to check if property cssRules exists in document.styleSheets[i] object?

How to check if property cssRules exists in document.styleSheets[i] object? 如何检查document.styleSheets [i]对象中是否存在属性cssRules?

I have found out that I cannot use 我发现我不能使用

if ( sheets[i].hasOwnProperty("cssRules") )
  because .cssRules is inherited property.

But when I try to use 但是当我尝试使用

if( sheets[i].cssRules !== undefined )

so in debugger (Firefox 48 Toolbox tool) I got exception: SecurityError. 因此,在调试器(Firefox 48工具箱工具)中,出现异常:SecurityError。

For this reason the code fails. 因此,代码失败。

var cssList = function(node) {
    var sheets = document.styleSheets, o = {};
    var sheet;
    for (var i in sheets) {
      if( sheets[i].cssRules !== undefined )
        sheet = sheets[i].cssRules;
      else
      if( sheets[i].rules !== undefined )
        sheet = sheets[i].rules;
      else
        continue;

      var rules = sheets[i].rules || sheets[i].cssRules;
    }
    return o;
}

You can use 'cssRules' in sheets[i] to detect if sheets[i] has a cssRules property. 您可以'cssRules' in sheets[i]使用'cssRules' in sheets[i]来检测sheets[i]是否具有cssRules属性。

However, all stylesheets should have a cssRules property, and then you will always get true . 但是,所有样式表都应具有cssRules属性,然后您将始终获得true

Your problem is that the cssRules getter throws an error for security reasons. 您的问题是,出于安全原因, cssRules getter会引发错误。

I think the only way to detect that is with a try statement: 我认为唯一的检测方法是使用try语句:

try {
  var rules = sheets[i].cssRules;
} catch(err) {}
if(rules) // ...

sheet instanceof CSSStyleSheet or ("cssRules" in sheet) sheet instanceof CSSStyleSheet("cssRules" in sheet)

SecurityError 安全错误

That's possibly a SOP violation, depending on from where you got the node and document objects in question 可能是违反SOP的情况,具体取决于您从何处获得有问题的节点和文档对象

The CSSOM spec says CSSOM规范说

If the origin-clean flag is unset, throw a SecurityError exception. 如果未设置origin-clean标志,则引发SecurityError异常。

which is only set if allowed by CORS headers or SOP. 仅在CORS标头或SOP允许的情况下设置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM