Firefox not able to enumerate document.styleSheets[].cssRules[]

若如初见. 提交于 2019-11-29 03:40:34

You can get that error when trying to read a stylesheet loaded from a different domain or server, or trying to read an @import rule.

For your purpose, just check the document.styleSheets.length .

As of 2013, you can set the "crossorigin" attribute on the <link>-Element to signal the browser that this CSS is trusted (https://developer.mozilla.org/en-US/docs/Web/HTML/Element/link).

After that, you can access its rules via Javascript.

jishi

You are loading css-files from another domain, I guess that you are not allowed to modify cssRules for externally loaded css files.

see this: Accessing cross-domain style sheet with .cssRules

The stylesheet is there and works fine, you just cannot access the cssRules property of the stylesheet because it is set to null by the browser.

The security error you get is due to the same origin policy - you are working on stylesheets from another domain, you will not have this problem if the stylesheets are hosted on the same domain your webpage is.

Achilleterzo

Try with condition: (IE workaround)

function aftermath(index) {
    var css = document.styleSheets[index].rules || document.styleSheets[index].cssRules;
    alert(css.length);
}

This is giving the error:

aftermath(document.styleSheets.length - 1);

If i set it to 0 all work fine... The problem is that the css is not ready at this time, if you need to access it, you need to do that in a second moment

Last edit:

If you whant keep css updated from source, you can use a php proxy for loading it:

<?php
$name = 'http://ajax.googleapis.com/ajax/libs/jqueryui/$_GET[version]/themes/$_GET[theme]/jquery-ui.css';
$fp = fopen($name, 'rb');
fpassthru($fp);
exit;
?>

Then you can get it using e.g. /proxy.php?version=1.7.0&theme=humanity

You can put the failing line in a try-catch block. That's how i solved the same issue on one project.

Try window.document.styleSheets[x].cssRules.length instead of document.styleSheets[x].cssRules.length. It will work on firefox without any security exception.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!