title: Javascript/jQuery XSS potential reading from query strings
body: <p>My javascript reads data from a query string and puts that data into a text box using <code>jQuery.val()</code>.</p>
  
  <p>This works fine but I am wondering is this safe from XSS attacks?</p>
  
  <p>Say the query string looked like...</p>
  
  <p><code>site.com?q="javascript:alert(document.cookie)</code></p>
  
  <p>Which would effectively do:</p>
  
  <p><code>jQuery.val('"javascript:alert(document.cookie)')</code></p>
  
  <p>From what I have tested in IE8 / firefox this sets the input value as seen and doesn't do the actual injection.</p>
  
  <p>If I run this function over the string first:</p>
  
  <pre><code>function htmlEncode(str) {
      return str.replace(/&lt;/g, '&amp;lt;').replace(/&gt;/g, '&amp;gt;').replace(/'/g, '&amp;#039;').replace(/"/g, '&amp;quot;');
  }
  </code></pre>
  
  <p>Then you literally see <code>&amp;quot;javascript:alert(document.cookie)</code> in the input value which is not what I want.</p>
  
  <p>Using jQuery 1.5.2 I guess my question is does <code>jQuery.val()</code> handle the HTML entities for you and is therefore considered safe?</p>