简体   繁体   English

使用jQuery的.html()函数转义内容以进行放置

[英]Escaping content for placement with jQuery's .html() function

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. 稍后,我要将已经转义到HTML实体的输入复制到文本区域,以便可以对其进行编辑。 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. 但是,jQuery的jQuery.html()函数读取HTML实体,就好像它们是真实的HTML一样,并将用户脚本直接注入到页面中。 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. 我需要获取用户输入的内容,即使它包含<script>标记,也要输出到可以在其中进行编辑的textarea。

So, I need this: 所以,我需要这个:

<textarea name="empty"></textarea>
<div name="user-input"> &lt;script&gt; window.alert('hi'); &lt;/script&gt; </div>

to become this: 成为这个:

<textarea name="empty"> &lt;script&gt; window.alert('hi'); &lt;/script&gt; </textarea>
<div name="user-input"> &lt;script&gt; window.alert('hi'); &lt;/script&gt; </div>

on JavaScript trigger. 在JavaScript触发器上。 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. 显示一个空的文本框,并将用户的JavaScript注入页面。

Right now I am getting the contents of user-input and placing them into the textarea like so: 现在,我正在获取用户输入的内容,并将其放入文本区域,如下所示:

 $('#edit-textarea').html(($('#user-input').text()));

I've tried several variations of this to no avail. 我已经尝试了几种变种,但都没有用。

Please see http://jsfiddle.net/vkRkt/8 for a test case. 有关测试案例,请参见http://jsfiddle.net/vkRkt/8

EDIT: 编辑:

See discussion below. 请参阅下面的讨论。 The solution in my case was to use jquery.val() instead of jquery.html() . 在我的情况下,解决方案是使用jquery.val()而不是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. 我跳过了val,因为我觉得它是jquery.attr('value', new_value)的别名,它有自己的注入问题(可以用“停止” val()attr('value', val)并在我的简短测试中似乎可以安全地进行注入尝试。

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. 如果以后有人遇到此问题,并且知道val实际上不是这样做的安全方法,请立即回答并更新我们。

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. 我还尝试使用.text()而不是.val() ,它当然也保留了转义.val() Don't use .html() if you don't want the data to be HTML. 如果您不希望数据为HTML,请不要使用.html()

jsFiddle Demo jsFiddle演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM