I am trying to create a bookmarklet that reads a website's CSS media queries and adds CSS rules depending on the result. But I usually can't even access a page's CSS file. Here's what I've tried so far (this is all in-page JS code that assumes the presence of JQuery):
var styleSheet = document.styleSheets.item(0);
var rules = styleSheet.cssRules;
This fails with
Exception: The operation is insecure.
I'm using Firefox and think that this approach usually works in other browsers, but I need this to work across browsers. I can't enable JSONP
or CORS
on the server because I don't have access to the server. So I take a different tack.
$.ajax({
url: styleSheet.href,
type: "GET",
success: function(data, textStatus, jqXHR) {
console.log('data: '+data+", textStatus: "+textStatus+"\nObject: "+data);
},
error: function(jqXHR, textStatus, error) {
console.error("Failed. jqXHR: "+JSON.stringify(jqXHR)+"\ntextStatus:"+textStatus+"\nerror: "+error);
}
});
This returns 200
every time, but works very infrequently, and gives me no information of why it fails:
Failed. jqXHR: {"readyState":0,"responseText":"","status":0,"statusText":"error"}
textStatus: error
error:
(I also tried a plain $.get
, but hoped the above would tell me why it was failing). If you know how to get more info out of a request, let me know.
Because I'm looking for media queries, I need access to the CSS file and can't just look at elements' calculated CSS.
I'm not trying to change the CSS file, just apply apply new CSS to elements, so I don't see why it should be considered insecure.
Finally, the fact that I can clearly see a page's CSS in the style editor or by navigating to the URL I get from styleSheet.href
means that it should be accessible programatically. If possible, a solutions that works on https
pages as well would be amazing.