Is there a way to execute javascript from inside a css file ? - javascript

I have access ONLY to a css file which I can modify. I have a lot of modifications to do and I want to know if there is a way to execute a javascript code from inside a CSS file.
I did find an old vulnerability that is not supported in up-to-date browsers any more.
http://dougrathbone.com/blog/2013/10/30/executing-javascript-inside-css-another-reason-to-whitelist-and-encode-user-input
As you can see the vulnerability was exploited by calling an arbitrary code from another url like this
body {
behavior:url(/user/uploadedfiles/evil-uploaded-component.htc);
}
Now, I want to know if there's any alternative way to do that ?

IE and Firefox both contain ways to execute JavaScript from CSS. As Paolo mentions, one way in IE is the expression technique, but there's also the more obscure HTC behaviour, in which a separate XML that contains your script is loaded via CSS. A similar technique for Firefox exists, using XBL. These techniques don't execute JavaScript from CSS directly, but the effect is the same.
HTC with IE
Use a CSS rule like so:
body {
behavior:url(script.htc);
}
and within that script.htc file have something like:
<PUBLIC:COMPONENT TAGNAME="xss">
<PUBLIC:ATTACH EVENT="ondocumentready" ONEVENT="main()" LITERALCONTENT="false"/>
</PUBLIC:COMPONENT>
<SCRIPT>
function main()
{
alert("HTC script executed.");
}
</SCRIPT>
The HTC file executes the main() function on the event ondocumentready (referring to the HTC document's readiness.)
XBL with Firefox
Firefox supports a similar XML-script-executing hack, using XBL.
Use a CSS rule like so:
body {
-moz-binding: url(script.xml#mycode);
}
and within your script.xml:
<?xml version="1.0"?>
<bindings xmlns="http://www.mozilla.org/xbl" xmlns:html="http://www.w3.org/1999/xhtml">
<binding id="mycode">
<implementation>
<constructor>
alert("XBL script executed.");
</constructor>
</implementation>
</binding>
</bindings>
All of the code within the constructor tag will be executed (a good idea to wrap code in a CDATA section.)
In both techniques, the code doesn't execute unless the CSS selector matches an element within the document. By using something like body, it will execute immediately on page load.

Related

is css syntax incompatible in .js

why can't a css file be included in a .js?
in other words, why can't <style></style> syntax be included in a .js file? the js script and css works on my page when where are in the header but when I call them externally, the css fails?
People who implemented <script> and <style> 15 or 20 years ago decided not to do that.
Things moved very, very fast in the 90s, in some ways at least.
Note that JavaScript pre-dated CSS by a couple of years. They were developed and driven by different companies. By the time CSS was invented, modifying browser JavaScript parsers to understand CSS blocks was a very unlikely thing to happen (and, in fact, it didn't).
Here's a guess: you moved one or more <script>...</script> blocks along with one or more <style> ... <style> blocks into a single file, and then tried to import it with a <script src="something"></script> tag. That won't work. Your external JavaScript and CSS files need to be pure JavaScript and pure CSS.
Because you cannot style javascript, styles apply for html tags. If you include a style tag in a javascript file, what would the styles apply for?
I don't know of any way of including pure css in to a .js file, But there's an alternative.
You could use #getElementById().style.
Its not really practical but it's the only way that I know of.
There are several reasons:
Cascading StyleSheets are describing how things look on your web page whereas JavaScript describes how things behave – they are used for completely different things.
Websites should work without having JavaScript enabled. At least that's what I learned in the early days. If you included straight CSS in your JavaScript and the browser had JavaScript disabled then you wouldn't see those styles applied.
A .js file only contains Javascript. It's not an HTML file, so it isn't parsed for any kinds of <tagname> codes. You can't put <style> in it for the same reason that you don't surround the code with <script>...</script> inside the file (if you do this you'll get an error, because it's not Javascript). The contents of the file are treated like the contents inside a <script>...</script> block, and you're not allowed to put <style> in there, either -- it's only script code.

How does the browser identify inline JavaScripts?

I’m new to JavaScript. Started learning a few days back. Please correct me if I’m wrong anywhere. I came through the three representation of JavaScripts: “Inline”, “Embedded” and “External”.
I have two questions regarding this:
1. Example below: Here we are not mentioning <script type="text/javascript"> but still it is working fine and the browser identifies it. How is this happening?
<html>
<head>
<title></title>
</head>
<body>
<input type="Button" value="Click me" onclick="alert('Welcome');"/>
</body>
</html>
2. When to use inline and when to use embedded? I understand everything should be external because if the code is separate, it can be more easily cached by browsers (from this answer). But I didn’t get the usage of inline and embedded.
My question may sound a little simple, but I can’t find the answers to them through searching. Kindly help me to understand these basics better.
Here we are not mentioning but still it is working fine and the browser identifies it. How is this happening?
Because the HTML specification defines what intrinsic event attributes like onclick mean, just as it defines what <script> means.
When to use inline and when to use embedded?
In general:
Don't use intrinsic event attributes (like onclick="..."), bind event handlers using JavaScript (e.g. addEventListener).
Use external script elements (like <script src="..."></script>) for most scripts, especially if they large or reused between pages.
Consider inline script elements (like <script>...</script>) if:
the script is short and only applicable to a single page (you might get mild performance benefits or ease maintenance)
the script is designed to make data available to JavaScript (e.g. if it defines a variable containing frequently updated data and is generated from a database)
when browser reads html it's creating DOM. every element is object in DOM and has it's properties, events, functions. so when browser parses html it's binding events, calling functions at runtime. it's all about browser's behavior. look at: http://arvindr21.github.io/howBrowserWorks/ and http://www.html5rocks.com/en/tutorials/internals/howbrowserswork/ or search in google "how browser works"
it's good to separate js, css part from html. but sometimes You want output js functionality according logic of Your app: somebody inlines it, somebody dynamicaly generates js file and requires it in html.
From the code snippet in your question
<input type="Button" value="Click me" onclick="alert('Welcome');">
Is an example of inline JS.
The other varieties as you mentioned are embedded and external.
Embedded JS is useful in situations where your scripts are specific to that particular file alone. You cannot reuse your JS in any other file.
<script>
// Your script
</script>
External JS is useful in situations you want to reuse your script. For example create a file, hello.js with content
alert('Hello');
Then you can include the script in your html like
<script src="hello.js"></script>
Well, you can have external. This is javascript you load through an extrnal file
<Script type="text/javascript" src="path/to/javascript.js"></script>
Then you have embedded
<script type="text/javascript">
function foo() {
alert('bar');
}
foo();
</script>
Then you have inline. Imho(imho = In my humble opinion) inline comes in two varieties. inline functions or onclick handlers like you have shown.
The greater consensus is however that inline functions are where HTML code mixes with javascript like the example below.
<input type="button" onclick="foo()">
or an inline function as I and a few other developpers see it. Please note, this is my interpretation of the meaning inline. That interpretation is: A variable to which you assign a function.
Please note, this is an interpretation, but the meaning inline is very
vague, but not specified somewhere. When you are used to programming
higher level programming languages like java or c, inline has a whole
different meaning and meanings can blur over from one language to
another. That is why I think this is also an inline function because
you can use it within a function do define a scoped function in a
closure, or assign it to onlcick handlers of a DOM element, etc...
var foo = function() {
alert('bar');
}
foo();
To answer your second question:
Don't use inline. It's valid to use, but it means copying over all the javascript between separate html files.
If you make it abstract so you access all identifiers by id, and use the javascript representations it will run a lot smoother, and will be easier to maintain.
document.getElementById('someobjectname')
gives you the object you want from within a js file.
If you attach some onload handlers to the document element you can fire up your javascript when the document has finished loading into the browser and then perform your magic on it.

Accessing SVG inside object with JS in Internet Explorer

I have a test page: http://benfrain.com/playground/svg-test/
On it I have inserted the same SVG a number of ways (img, object, inline, and background image)
I have also implemented the use method of re-using defs from within the SVG (only for the object insertion method and the 'inline' insertion method).
In the console you will see I am also attempting to access the SVG contents from each insertion method (I know img and background image should not be accessible via script - I'm just proving the point).
However, on any version of Internet Explorer (IE9+) the object insertion method fails to load the external CSS (as noted in the comments, IE requires the alternative linking mechanism) referenced from within (via xlink, you would see a 6px wide stroke if it was working) and it is not reachable via JavaScript (works in all the other evergreen browsers) (my mistake).
Can anyone clarify why? I've had a look through the spec: http://www.w3.org/TR/html5/embedded-content-0.html#the-object-element but I must confess some of the technicalities are beyond my comprehension.
Update:
Further to Robert's comments below I made some tweaks to the test page above.
Firstly, the object is accessible with script (rookie mistake). However, oddities still abound:
If the SVG has a link in this format: <?xml-stylesheet href="styles.css" type="text/css"?> then IE11 applies the styles within that stylesheet to the SVG whether it is inserted in the page via img, background-image, inline or object (Safari/Firefox/Chrome only apply the styles if the SVG is inserted inline or via object).
There is a w3c testsuite page for external <use>: http://www.w3.org/Graphics/SVG/Test/20110816/svg/struct-use-05-b.svg
The implementation matrix suggests that IE9 doesn't support external <use> I'm not sure why Firefox is listed as failing as I think even at that time it should have passed that particular test.
For the <object> issue, you need to run the script in the onload event of the <object> tag. I guess you just get lucky with the other UAs as you basically have a race condition.
Presumably IE doesn't support including stylesheets using html syntax. Try XML syntax instead: <?xml-stylesheet href="mystyle.css" type="text/css"?>
Allowing images to use external files is a privacy leak which is why Firefox, Chrome and Safari disallow it. If you converted the CSS to a data URL you could use a link element.

JavaScript - head, body or jQuery?

This question is just to clear some things up. Some things like this have been asked before, and this rounds them all up into one question - where should JavaScript go in the HTML document, or, more importantly, does it matter? So, one of the things I'm asking is, does
<head>
<script type="text/javascript">
alert("Hello world!");
</script>
</head>
at all differ (in terms of functionality) from
<body>
<!-- Code goes here -->
<script type="text/javascript">
alert("Hello world!");
</script>
</body>
More importantly, I want to focus on JS that modifies or uses elements from the DOM in any way. So I know that if you put something like document.getElementById("test").innerHTML = "Hello world!" before <element id="test"></element> in your body, then it won't work since the body is loaded from top to bottom, making the JS load first, which will then proceed to try to manipulate an element that doesn't exist yet. So it should, just like the above, either go in the <head> or just before the </body> tag. The question is, aside from organisation and sorting, does it matter which one of these is chosen, and if so, in what way?
Of course, there is also a third method - the jQuery way:
$(document).ready(function(){ /*Code goes here*/ });
That way, it doesn't matter where in the body you place the code, since it will only be executed when everything has loaded. The question here is, is it worth importing a huge JS library just to use a method the need for which could be replaced with an accurate placing of your scripts? I'd just like to clear things up a little here, if you would like to answer, go ahead! Summary: where should different kinds of scripts go - head or body, and/or does it matter? Is jQuery worth it just for the ready event?
Most recommended method is to put it before </body> tag. Yahoo performance article also suggests that other than YSlow and Page Speed addons by Yahoo and Google respectively.
Quoting from Yahoo article linked above:
The problem caused by scripts is that they block parallel downloads.
The HTTP/1.1 specification suggests that browsers download no more
than two components in parallel per hostname. If you serve your images
from multiple hostnames, you can get more than two downloads to occur
in parallel. While a script is downloading, however, the browser won't
start any other downloads, even on different hostnames.
When you put scripts in <head> tag, the browsers goes for them thereby keeping other stuff on hold until scripts are loaded which users will perceive like slow loading of the page. This is why you should put scripts at the bottom.
As for:
$(document).ready(function(){/*Code goes here*/});
It is fired when DOM is available and ready to be manipulated. If you put your code at the end, you won't necessarily need this but usually this is needed because you want to do something as soon as DOM is available for use.
Although common practice, putting script tags in the head is not usually a good idea, as it holds up the rendering of your page until those scripts have been downloaded and processed (barring your use of async or defer and the browser supporting them).
The usual recommendation is to put script tags at the very end of the body tag, e.g., just before </body>. That way, all of the DOM elements above the script will be accessible (see links below). One caveat on that is that there can be a brief moment when your page has been at least partially-rendered but your scripts not processed (yet), and if the user starts interacting with the page, they may do something to raise an event that your script hasn't had time to hook yet. So you need to be aware of that. This is one reason for progressive enhancement, which is the idea that the page will work without JavaScript, but work better with it. If you're doing a page/app that just won't work without JavaScript at all, you might include some inline script at the top of the body tag (e.g., <script>minimal code here</script>) that hooks any bubbling events on document.body and either queues them for action when your script is loaded, or just asks the user to wait.
Using features like jQuery's ready is fine, but not really necessary outside of libraries (e.g., if you're in control of where the script tags will be, you don't usually need to use it; but if you're writing a jQuery plug-in that needs to do something on load [which is relatively rare, normally they just wait to be called], you usually do).
More reading:
YUI Best Practices for Speeding Up your Website
Google on when the DOM will be ready
It is possible to download javascripts in parallel by doing something like this:
(function () {
var ele = document.createElement('script');
ele.src = "https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js";
ele.id = "JQuery";
ele.onload = function () {
//code to be executed when the document has been loaded
};
document.getElementsByTagName('head')[0].appendChild(ele);
})();
In the example it downloads minified JQuery v1.7.2 from Google, this is a good way to download JQuery since downloading it from Google is like using a CDN and if the user has been on a page that used the same file it might be cached and therefor doesn't need to be downloaded
There is a really good Google tech talk about this here http://www.youtube.com/watch?v=52gL93S3usU&feature=plcp

Downloading javascript Without Blocking

The context: My question relates to improving web-page loading performance, and in particular the effect that javascript has on page-loading (resources/elements below the script are blocked from downloading/rendering).
This problem is usually avoided/mitigated by placing the scripts at the bottom (eg, just before the tag).
The code i am looking at is for web analytics. Placing it at the bottom reduces its accuracy; and because this script has no effect on the page's content, ie, it's not re-writing any part of the page--i want to move it inside the head. Just how to do that without ruining page-loading performance is the crux.
From my research, i've found six techniques (w/ support among all or most of the major browsers) for downloading scripts so that they don't block down-page content from loading/rendering:
(i) XHR + eval();
(ii) XHR + inject;
(iii) download the HTML-wrapped script as in iFrame;
(iv) setting the script tag's async flag to TRUE (HTML 5 only);
(v) setting the script tag's defer attribute; and
(vi) 'Script DOM Element'.
It's the last of these i don't understand. The javascript to implement the pattern (vi) is:
(function() {
var q1 = document.createElement('script');
q1.src = 'http://www.my_site.com/q1.js'
document.documentElement.firstChild.appendChild(q1)
})();
Seems simple enough: and anonymous function is created then executed in the same block. Inside this anonymous function:
a script element is created
its src element is set to it's location, then
the script element is added to the DOM
But while each line is clear, it's still not clear to me how exactly this pattern allows script loading without blocking down-page elements/resources from rendering/loading?
One note first:
(iv) setting the script tag's 'async' flag to 'TRUE' (HTML 5 only);
async is a "boolean attribute", in the HTML sense. That means that either of the following is correct:
<script async src="..."></script>
<script async="" src="..."></script>
<script async="async" src="..."></script>
And that both of the following make the script be loaded asynchronously, but are not conforming (because of the possible confusion):
<script async="true" src="..."></script>
<script async="false" src="..."></script>
Now on your question. The point is that it is the HTML parser that is being blocked by the script (because people do stupid things things like document.write("<!--"), even from external JS files, and expect it to "work"). However, in your case (vi), the HTML parser doesn't ever see the script element, because it is added to the DOM directly. Somewhat logically, if a script element (or rather, a <script> start tag) isn't seen by the HTML parser, it can't stop the parsing either.
I will try to say everything with one URL, it will save us both time.
Please have a look at this presentation from the author of a book that addresses topics such as the ones you are mentioning. I found the presentation (there is a youtube one also - i think in the google channel) very very interesting. It explains much of what you want to know.
http://www.slideshare.net/souders/sxsw-even-faster-web-sites
http://www.youtube.com/watch?v=aJGC0JSlpPE (long video many details on performance params/topics)
Your last example modifies the DOM tree and can only be used after the DOM tree is complete (onload). So the browser is already able to fully render the page, while you're loading the js script.
Here is a example how firefox renders 2 different versions:
img http://img177.imageshack.us/img177/9302/40229406.jpg
test.html loads with your method above within onload at the bottom of the page.
test2.html loads with an simple script tag in head.
Note the red line, this is when the onload element is triggered.

Categories