Reputation: 3621
How to check if property cssRules exists in document.styleSheets[i] object?
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.
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;
}
Upvotes: 0
Views: 879
Reputation: 288480
You can use 'cssRules' in sheets[i]
to detect if sheets[i]
has a cssRules
property.
However, all stylesheets should have a cssRules
property, and then you will always get true
.
Your problem is that the cssRules
getter throws an error for security reasons.
I think the only way to detect that is with a try
statement:
try {
var rules = sheets[i].cssRules;
} catch(err) {}
if(rules) // ...
Upvotes: 2
Reputation: 43117
sheet instanceof CSSStyleSheet
or ("cssRules" in sheet)
SecurityError
That's possibly a SOP violation, depending on from where you got the node and document objects in question
The CSSOM spec says
If the origin-clean flag is unset, throw a SecurityError exception.
which is only set if allowed by CORS headers or SOP.
Upvotes: 0