小编典典

JavaScript从输入字段读取属性时,HTML编码丢失

javascript

我正在使用JavaScript从隐藏字段中提取值并将其显示在文本框中。隐藏字段中的值被编码。

例如,

<input id='hiddenId' type='hidden' value='chalk &amp; cheese' />

被拉入

<input type='text' value='chalk &amp; cheese' />

通过一些jQuery从隐藏字段中获取值(在这一点上,我失去了编码):

$('#hiddenId').attr('value')

问题是,当我chalk &amp; cheese从隐藏字段读取内容时,JavaScript似乎丢失了编码。我不希望值是chalk & cheese。我希望amp;保留原义。

是否存在将对字符串进行HTML编码的JavaScript库或jQuery方法?


阅读 404

收藏
2020-04-22

共1个答案

小编典典

编辑:
此答案发布很久以前,并且该htmlDecode功能引入了XSS漏洞。已对其进行了修改,将临时元素从div改为textarea减少了XSS机会。但是如今,我鼓励您使用其他anwswer中建议的DOMParser
API 。


我使用以下功能:

function htmlEncode(value){
  // Create a in-memory element, set its inner text (which is automatically encoded)
  // Then grab the encoded contents back out. The element never exists on the DOM.
  return $('<textarea/>').text(value).html();
}

function htmlDecode(value){
  return $('<textarea/>').html(value).text();
}

基本上,textarea元素是在内存中创建的,但是永远不会附加到文档中。

htmlEncode函数上,我设置的innerText元素,并检索已编码的innerHTML;
htmlDecode函数上,我设置了innerHTML元素的值,并innerText检索到。

2020-04-22