有人知道一个简单的方法来转义HTML从字符串在jQuery?我需要能够传递一个任意字符串,并有它正确转义显示在HTML页面(防止JavaScript/HTML注入攻击)。我确信可以通过扩展jQuery来实现这一点,但目前我对框架的了解还不够,无法实现这一点。
当前回答
我增强了mustache.js示例,将escapeHTML()方法添加到字符串对象中。
var __entityMap = {
"&": "&",
"<": "<",
">": ">",
'"': '"',
"'": ''',
"/": '/'
};
String.prototype.escapeHTML = function() {
return String(this).replace(/[&<>"'\/]/g, function (s) {
return __entityMap[s];
});
}
这样就很容易使用"Some <text>, more Text&Text".escapeHTML()
其他回答
这是一个很好的安全的例子……
function escapeHtml(str) {
if (typeof(str) == "string"){
try{
var newStr = "";
var nextCode = 0;
for (var i = 0;i < str.length;i++){
nextCode = str.charCodeAt(i);
if (nextCode > 0 && nextCode < 128){
newStr += "&#"+nextCode+";";
}
else{
newStr += "?";
}
}
return newStr;
}
catch(err){
}
}
else{
return str;
}
}
如果你将这些信息保存在数据库中,使用客户端脚本转义HTML是错误的,这应该在服务器中完成。否则很容易绕过你的XSS保护。
为了让我的观点更清楚,这里有一个例子,使用其中的一个答案:
假设你正在使用函数escapeHtml来转义博客评论中的Html,然后将其发布到服务器上。
var entityMap = {
"&": "&",
"<": "<",
">": ">",
'"': '"',
"'": ''',
"/": '/'
};
function escapeHtml(string) {
return String(string).replace(/[&<>"'\/]/g, function (s) {
return entityMap[s];
});
}
用户可以:
编辑POST请求参数并用javascript代码替换注释。 使用浏览器控制台重写escapeHtml函数。
如果用户将这个代码段粘贴到控制台中,它将绕过XSS验证:
function escapeHtml(string){
return string
}
如果你转义HTML,只有三个我能想到,这将是真正必要的:
html.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
根据您的用例,您可能还需要执行“to "”之类的操作。如果列表足够大,我就使用数组:
var escaped = html;
var findReplace = [[/&/g, "&"], [/</g, "<"], [/>/g, ">"], [/"/g, """]]
for(var item in findReplace)
escaped = escaped.replace(findReplace[item][0], findReplace[item][1]);
encodeURIComponent()只会对url进行转义,而不会对HTML进行转义。
我写了一个小函数来做这个。它只转义“,&,<和>(但通常这就是你所需要的)。它比前面提出的解决方案稍微优雅一些,因为它只使用一个.replace()来完成所有的转换。(编辑2:降低代码复杂度,使函数更小更整洁,如果你对原始代码感到好奇,请参阅答案末尾。)
function escapeHtml(text) {
'use strict';
return text.replace(/[\"&<>]/g, function (a) {
return { '"': '"', '&': '&', '<': '<', '>': '>' }[a];
});
}
这是纯Javascript,没有使用jQuery。
逃避/和“too”
编辑以回应mklement的评论。
上面的函数可以很容易地扩展到包括任何字符。要指定更多要转义的字符,只需将它们插入正则表达式中的字符类(即在/[…]/g中)和chr对象中的一个条目中。(编辑2:用同样的方式缩短了这个函数。)
function escapeHtml(text) {
'use strict';
return text.replace(/[\"&'\/<>]/g, function (a) {
return {
'"': '"', '&': '&', "'": ''',
'/': '/', '<': '<', '>': '>'
}[a];
});
}
Note the above use of ' for apostrophe (the symbolic entity ' might have been used instead – it is defined in XML, but was originally not included in the HTML spec and might therefore not be supported by all browsers. See: Wikipedia article on HTML character encodings). I also recall reading somewhere that using decimal entities is more widely supported than using hexadecimal, but I can't seem to find the source for that now though. (And there cannot be many browsers out there which does not support the hexadecimal entities.)
注意:将/和'添加到转义字符列表中并不是很有用,因为它们在HTML中没有任何特殊含义,也不需要转义。
原始escapeHtml函数
编辑2:原始函数使用一个变量(chr)来存储.replace()回调所需的对象。这个变量还需要一个额外的匿名函数来限定它的范围,这使得函数(不必要地)变得更大更复杂。
var escapeHtml = (function () {
'use strict';
var chr = { '"': '"', '&': '&', '<': '<', '>': '>' };
return function (text) {
return text.replace(/[\"&<>]/g, function (a) { return chr[a]; });
};
}());
我还没有测试这两个版本中哪个更快。如果你喜欢,请在这里添加相关信息和链接。
因为你使用的是jQuery,你可以设置元素的text属性:
// before:
// <div class="someClass">text</div>
var someHtmlString = "<script>alert('hi!');</script>";
// set a DIV's text:
$("div.someClass").text(someHtmlString);
// after:
// <div class="someClass"><script>alert('hi!');</script></div>
// get the text in a string:
var escaped = $("<div>").text(someHtmlString).html();
// value:
// <script>alert('hi!');</script>
推荐文章
- 错误:'types'只能在.ts文件中使用- Visual Studio Code使用@ts-check
- React-Native:应用程序未注册错误
- LoDash:从对象属性数组中获取值数组
- 我如何在Swift连接字符串?
- src和dist文件夹的作用是什么?
- jQuery UI对话框-缺少关闭图标
- 如何使用AngularJS获取url参数
- 将RGB转换为白色的RGBA
- 如何将“camelCase”转换为“Camel Case”?
- 我们可以在另一个JS文件中调用用一个JavaScript编写的函数吗?
- 如何使用JavaScript重新加载ReCaptcha ?
- jQuery。由于转义了JSON中的单引号,parseJSON抛出“无效JSON”错误
- 如何获得一个变量值,如果变量名存储为字符串?
- 在Ruby中不创建新字符串而修饰字符串的规范方法是什么?
- 为什么不是字符串。空一个常数?