3

Is obtaining the value of a textarea/input with the jQuery function .val() XSS-proof?

<html>
    <textarea id="t1"></textarea>
    <script> 
        var toBeDisplayed = $('#t1').val();
        $('#elem').html(toBeDisplayed);
    </script>
</html>
eversor
  • 914
  • 4
  • 8
  • 22
  • 2
    You don’t have to care for where the value comes from (`$('#t1').val()`) but where it goes to (`$('#elem').html()`). – Gumbo Feb 28 '14 at 13:38

2 Answers2

5

As Gumbo mentioned in his comment, it does not matter what you read in, but it does matter what you display after the fact. To simply answer your question, no. jQuery's .val() does not have any filtering that will protect you from XSS. You could perhaps take in the value into var toBeDisplayed and then perform your own filtering before it gets relayed to be displayed again.

Jason Higgins
  • 647
  • 4
  • 8
  • 1
    What if I assign `toBeDisplayed` to another textarea using `jQuery.val()`, example: `$('#another-textarea').val(toBeDisplayed);`, Should I worry about XSS? – user3019105 Aug 03 '16 at 16:59
  • 2
    Can someone explain further? It seems to me that JQuery is simply using a direct `value` attribute assignment via the JS DOM API. What attacks are possible in this case? See also this SO article: https://security.stackexchange.com/questions/139749/in-what-situations-can-element-setattribute-allow-xss – Eric Nguyen Sep 11 '17 at 23:13
  • 1
    @EricNguyen - as far as I know, you are correct, and val() can't cause XSS under any conditions as it doesn't concatenate strings or any such, it creates DOM nodes through API. That would mean that this answer is 100% wrong. – Davor Jan 16 '18 at 13:04
0

Of course it is always safest to do the sanitizing on the server side before displaying the input back to the user. It can be done more quickly and easily in the browser, but any code running in the browser should not be considered entirety trusted; it could be modified or disabled.

Luke Sheppard
  • 2,217
  • 3
  • 15
  • 21