I need to accept arbitrary user input. Later, I want to copy that input, already escaped to HTML entities, into a textarea so it can be edited. However, jQuery's jQuery.html()
function reads out the HTML entities as if they were real HTML and injects the user script directly into the page. I need to grab the contents of the user input, even if it contains <script>
tags, and output to a textarea where it can be edited.
So, I need this:
<textarea name="empty"></textarea>
<div name="user-input"> <script> window.alert('hi'); </script> </div>
to become this:
<textarea name="empty"> <script> window.alert('hi'); </script> </textarea>
<div name="user-input"> <script> window.alert('hi'); </script> </div>
on JavaScript trigger. Instead, the textarea becomes:
<textarea name="empty"> <script> window.alert('hi'); </script> </textarea>
displaying an empty text box and injecting the user's JavaScript into the page.
Right now I am getting the contents of user-input and placing them into the textarea like so:
$('#edit-textarea').html(($('#user-input').开发者_StackOverflow社区text()));
I've tried several variations of this to no avail.
Please see http://jsfiddle.net/vkRkt/8 for a test case.
EDIT:
See discussion below. The solution in my case was to use jquery.val()
instead of jquery.html()
. I skipped over val because I was under the impression that it was an alias for jquery.attr('value', new_value)
, which has its own injection issues (can be stopped with a "). val()
is not the same as attr('value', val)
and appears safe from injection attempts in my brief testing.
If anyone runs across this later and knows that val
is actually not a safe way to do this, please answer and update us immediately.
Thanks.
$('#edit-textarea').val(($('#user-input').text()));
works fine for me. I also tried using .text()
instead of .val()
and it of course kept the escaping as well. Don't use .html()
if you don't want the data to be HTML.
jsFiddle Demo
精彩评论