从输入字段读取属性时 HTML 编码丢失 [英] HTML-encoding lost when attribute read from input field

查看:19
本文介绍了从输入字段读取属性时 HTML 编码丢失的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I’m using JavaScript to pull a value out from a hidden field and display it in a textbox. The value in the hidden field is encoded.

例如

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

被拉进来

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

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

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

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

问题是当我阅读chalk &amp;cheese 从隐藏字段来看,JavaScript 似乎丢失了编码.我不希望值是 chalk &奶酪.我希望保留文字 amp;.

The problem is that when I read chalk &amp; cheese from the hidden field, JavaScript seems to lose the encoding. I do not want the value to be chalk & cheese. I want the literal amp; to be retained.

是否有 JavaScript 库或 jQuery 方法可以对字符串进行 HTML 编码?

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

推荐答案

这个答案是很久以前发布的,htmlDecode 函数引入了一个 XSS 漏洞.它已被修改,将临时元素从 div 更改为 textarea 以减少 XSS 机会.但是现在,我鼓励您按照其他答案中的建议使用 DOMParser API.

This answer was posted a long ago, and the htmlDecode function introduced a XSS vulnerability. It has been modified changing the temporary element from a div to a textarea reducing the XSS chance. But nowadays, I would encourage you to use the DOMParser API as suggested in other anwswer.

我使用这些功能:

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 元素是在内存中创建的,但它永远不会附加到文档中.

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

htmlEncode 函数中,我设置了元素的innerText,并检索了编码后的innerHTML;在 htmlDecode 函数上,我设置了元素的 innerHTML 值,然后检索了 innerText.

On the htmlEncode function I set the innerText of the element, and retrieve the encoded innerHTML; on the htmlDecode function I set the innerHTML value of the element and the innerText is retrieved.

此处检查运行示例.

这篇关于从输入字段读取属性时 HTML 编码丢失的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆