views:

1039

answers:

3

I'm looking at this Railscast episode and wondering why the call to escape_javascript is needed here:

$("#reviews").append("<%= escape_javascript(render(:partial => @review)) %>");

What is escape_javascript used for?

According to the Rails docs:

escape_javascript(javascript)

Escape carrier returns and single and double quotes for JavaScript segments.

But that doesn't mean much to me.

+2  A: 

Because you don't want users posting JavaScript that the browser actually executes?

Azeem.Butt
+2  A: 

users may post malicious code (malicious users) that if left unescaped will potentially get executed, allowing users to control your application.

try this:

<% variable = '"); alert("hi there' %>
$("#reviews").append("<%= variable %>");

not really familiar with the syntax of rails, but if you don't escape variable then an alert box will show, and i dont think that is intended behaviour.

barkmadley
+2  A: 

It's easier to understand if you split the code in two parts.

The first part $("#reviews").append("...") is rjs. This means that it is ruby code that will get transformed to javascript code and then sent to the client. This piece concretely will use javascript to add something to any dom node with class "reviews" - but that is not important for your question. What is important is that you will be generating javascript.

Another important thing to take into account is that in this particular case, the javascript uses a string, generated by ruby - the "...". It is one string with double quotes(""). Hold on to that knowledge piece for a moment.

Now think of what render(:partial => @review) is doing.

It is rendering a partial - which means that it could be rendering any kind of code - html, css ... or even more javascript!

So, what happens if our partial renders something like this?

<a href="/mycontroller/myaction">Action!</a>

Remember that your javascript was taking a double-quoted string as a parameter? Now see what you are generating - inmediately after the href= there is a double quote character! That will close your string before it should!

$("#reviews").append("<a href="/mycontroller/myaction">Action!</a> ") #gives you an error

In order for this not to happen, you want to escape these special characters so your string is not cut - like this:

<a href=\"/mycontroller/myaction\">Action!</a>

This is done by using escape_javascript.

$("#reviews").append("<a href=\"/mycontroller/myaction\">Action!</a>")

Regards!

egarcia