如何在javascript中处理可能的HTML编码值

时间:2013-08-05 14:46:23

标签: javascript jquery html encoding decoding

我有一种情况,我不确定我得到的输入是否是HTML编码。我该如何处理?我也有jQuery可用。

function someFunction(userInput){
    $someJqueryElement.text(userInput);
}

// userInput "<script>" returns "&lt;script&gt;", which is fine
// userInput "&lt;script&gt;" returns &amp;lt;script&amp;gt;", which is bad

我可以避免逃避&符号(&),但有什么风险呢?非常感谢任何帮助!

重要说明:此用户输入不在我的控制范围内。它从外部服务返回,有人可能会篡改它并避免该服务本身提供的html转义。

2 个答案:

答案 0 :(得分:2)

你真的需要确保避免这些情况,因为它引入了很难预测的条件。

尝试向函数添加其他变量输入。

function someFunction(userInput, isEncoded){
    //Add some conditional logic based on isEncoded
    $someJqueryElement.text(userInput);
}

如果查看fckEditor等产品,可以选择编辑源代码或使用富文本编辑器。这可以防止需要自动编码检测。

如果您仍然坚持自动检测html编码字符,我建议使用index of来验证某些关键短语是否存在。

str.indexOf('&lt;') !== -1

上面的这个例子将检测到&lt;字符。

~~~在此行下方编辑后添加了新文字。~~~

最后,我建议查看this answer。他们建议使用解码功能并检测长度。

var string = "Your encoded &amp; decoded string here"

function decode(str){
    return decodeURIComponent(str).replace(/&lt;/g,'<').replace(/&gt;/g,'>');
}

if(string.length == decode(string).length){
    // The string does not contain any encoded html.
}else{
    // The string contains encoded html.
}

同样,这仍然存在用户通过输入那些特殊编码的字符来伪造过程的问题,但这就是html编码。因此,只要其中一个字符序列出现,就应该采用html编码。

答案 1 :(得分:1)

您必须始终正确编码不受信任的输入,然后再将其连接成HTML等结构化语言。

否则,您将启用XSS等注入攻击。

如果输入应包含HTML格式,则应使用清理程序库来删除所有可能不安全的标记&amp;属性。

您还可以使用正则表达式/<|>|&(?![a-z]+;)来检查字符串是否包含任何非编码字符;但是,您无法区分已编码的字符串与谈论编码的未编码字符串。