CSS metadata return

I have a CSS stylesheet dynamically created on the server and returned using the <link> . Is it possible to return any metadata with this stylesheet that I could read using JavaScript?

(Usage example: the stylesheet I am returning is a combination of several smaller ones. I want my JavaScript code to be able to determine which ones were included.)

I thought about adding some special properties to the element:

 body { -my-custom-prop1:0; -my-custom-prop2:0; } 

But when I try to read them with:

 window.getComputedStyle(document.body)['-my-custom-prop1'] 

they do not return. Any other ideas?

EDIT: I changed the approach a bit. Instead of adding the <link> I made an AJAX request to retrieve the stylesheet and added its text to the <style> . That way, I could use HTTP response headers to include metadata. Of course, this will not work in different domains, for example, the <link> .

+7
source share
3 answers

See example of the following →

Although I believe this method is not recommended, this is what I developed to test Chrome, FF, Safari, and IE8.

First, I selected the list-style-image property, which will be used to store metadata, since it can contain any string in the url() parameter and still will not be used under any normal circumstances in the CSS body.

Then I applied a generic cross-browser function to getComputedStyle , since it is not available in all browsers.

Then I analyzed the return property to get only data in url('') , as a result we get the following functions:

 var getStyle = function(el, cssprop) { if (el.currentStyle) { return el.currentStyle[cssprop]; } else if (document.defaultView && document.defaultView.getComputedStyle) { return document.defaultView.getComputedStyle(el, "")[cssprop]; } else { return (el.style) ? el.style[cssprop] : 0; } }; var pullCSSMeta = function() { var aMeta = getStyle(document.body, 'listStyleImage').split('/'), meta = aMeta[aMeta.length - 1]; return decodeURIComponent(meta.substr(0, meta.length - 1).replace(/"$/,'')); }; 

If you need to store more than one piece of information, you can tarnish the data or potentially even save a JSON string. I hope you have a good reason for wanting to do this, as I think there are better ways to store metadata ... but there you go!

See example →

+3
source

The returned object is actually the CSS 2.1 values ​​used, not the calculated values. https://developer.mozilla.org/en/DOM/window.getComputedStyle

You may be able to poll these styles using another method: http://www.hunlock.com/blogs/Totally_Pwn_CSS_with_Javascript

+2
source

I asked a related question a while ago. Turns out you need to manually parse the stylesheet using javascript. I decided that I should not worry and found another solution to my problem. You could use some tricky tricks, such as the standard properties on dummy classes, which I think.

+1
source

All Articles