title: Protecting from XSS in escape_javascript() output in Rails
body: <p>In an application I am working on, a client-side view is generated based on some records in the database. I am first generating JSON of the records, saving it in a variable in my page, then using JS to build the interface.</p>
  
  <p>The problem is that the records contain user-generated fields, and the application is thus susceptible to XSS. If you let the JSON pass through <code>escape_html</code> (by not calling <code>html_safe</code> on it), it will screw up the quotes. </p>
  
  <p>To get to the code. In my model:</p>
  
  <pre><code>Class Foo
    # ...
    def describe_for_view
      [{:title =&gt; "hello", :content =&gt; "&lt;script&gt;I.Am.Evil()&lt;/script&gt;"}]
    end
  end
  </code></pre>
  
  <p>Somewhere in my view:</p>
  
  <pre><code>&lt;script&gt;
    var describedForView = $.parseJSON("&lt;%= escape_javascript(@foo.describe_for_view.to_json).html_safe %&gt;");
  &lt;/script&gt;
  </code></pre>
  
  <p>Then in my javascript:</p>
  
  <pre><code>$("body").append("title: " + describedForView[0].title + ", content: " + describedForView[0].content);
  </code></pre>
  
  <p>What I am currently doing is that I am wrapping the access to the user-generated fields with a call to <code>$.sanitize</code> as defined by:</p>
  
  <pre><code>$.sanitize = function(str) {
    return $("&lt;div/&gt;").text(str).html();
  };
  </code></pre>
  
  <p>Things work this way, but I don't think it is clean.</p>
  
  <p>Any suggestions?</p>