Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
385 views
in Technique[技术] by (71.8m points)

javascript - 从输入字段读取属性时,HTML编码丢失(HTML-encoding lost when attribute read from input field)

I'm using JavaScript to pull a value out from a hidden field and display it in a textbox.

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

The value in the hidden field is encoded.

(隐藏字段中的值被编码。)

For example,

(例如,)

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

gets pulled into

(被拉入)

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

via some jQuery to get the value from the hidden field (it's at this point that I lose the encoding):

(通过一些jQuery从隐藏字段中获取值(此时我失去了编码):)

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

The problem is that when I read chalk &amp; cheese

(问题是,当我阅读chalk &amp; cheese)

chalk &amp; cheese from the hidden field, JavaScript seems to lose the encoding.

(从隐藏字段起, chalk &amp; cheese似乎失去了编码。)

I do not want the value to be chalk & cheese .

(我不希望这个价值是chalk & cheese 。)

I want the literal amp;

(我想要文字amp;)

to be retained.

(被保留。)

Is there a JavaScript library or a jQuery method that will HTML-encode a string?

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

  ask by AJM translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

EDIT: This answer was posted a long ago, and the htmlDecode function introduced a XSS vulnerability.

(编辑:这个答案很久以前发布了,并且htmlDecode函数引入了XSS漏洞。)

It has been modified changing the temporary element from a div to a textarea reducing the XSS chance.

(已对其进行了修改,将临时元素从div更改为textarea从而减少了XSS机会。)

But nowadays, I would encourage you to use the DOMParser API as suggested in other anwswer .

(但是,如今,我鼓励您使用其他anwswer中建议的DOMParser API。)


I use these functions:

(我使用以下功能:)

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();
}

Basically a div element is created in memory, but it is never appended to the document.

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

On the htmlEncode function I set the innerText of the element, and retrieve the encoded innerHTML ;

(在htmlEncode函数上,我设置了元素的innerText ,并检索了编码的innerHTML ;)

on the htmlDecode function I set the innerHTML value of the element and the innerText is retrieved.

(在htmlDecode函数上,我设置了元素的innerHTML值,并检索了innerText 。)

Check a running example here .

(在此处查看运行示例。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.8k users

...