rails/rails — pull request #5127 by benmmurphy (2012-02-22 14:15:41+00:00)
Title: escape_javascript helper corrupts strings

<%= javascript_tag do %>

window.myvar = '<%= j "\u2028\\\r\n\"'<>&" %>';
alert(JSON.stringify(window.myvar));
<% end %>

this produces the following output:

"&#x2028;\\\n"'<>&"

this happens because the content of a script tag is not interpreted as html except for certain sequences which look like a closing tag to the browser. but rails escapes &,>,<," which means the values end up getting escaped too many times.

I think this is quite unexpected behaviour but may be a feature because it stops xss attacks caused by the user doing something like:

my_element.innerHtml = window.myvar;

i've added a new method to the helper called escape_javascript_string that doesn't cause the value of the string to be modified. it does this by changing html characters to unicode javascript escapes. example:

<%= javascript_tag do %>

window.myvar2 = '<%= escape_javascript_string "\u2028\\\r\n\"'<>&" %>';

alert(JSON.stringify(window.myvar2));
<% end %>

which produces the following output (chrome JSON.stringify doesn't escape unicode new line):

"
\\\r\n\"'<>&"