背景:
做快站项目碰到的一个bug,一图胜千言,bug如下图:
这个题目只在某些帐号下涌现,绝大数其他帐号都是一般的,一般情况下是这个模样的:
为啥会因帐号罢了呢?猜想是因为前端衬着模板所用的数据惹得祸 :(
剖析
检察DOM构造:
一般情况下,蓝框内的一切li
标签应当都在红筐内。
再看衬着模板用的数据:
果真,数据内里含有html
标签,可我在衬着模板之前没有做转义处置惩罚,恩,XSS
进击就是这么来的。
解决方案
jQuery 完成
html
转义
function htmlEncode(value){
return $('<div/>').text(value).html();
}
//Html解码猎取Html实体
function htmlDecode(value){
return $('<div/>').html(value).text();
}
借助
text()
和html()
函数来转译html
text()
: 要领猎取/设置的是婚配元素的文本内容,且会将HTML
中的预留字符(如大于号(>))转换成html
字符实体,以便于准确显现.html()
: 要领是猎取/设置婚配元素的html
内容。
javascript
完成html
转译
//编码
function html_encode(str)
{
var s = "";
if (str.length == 0) return "";
s = str.replace(/&/g, ">");
s = s.replace(/</g, "<");
s = s.replace(/>/g, ">");
s = s.replace(/ /g, " ");
s = s.replace(/\'/g, "'");
s = s.replace(/\"/g, """);
s = s.replace(/\n/g, "<br>");
return s;
}
//解码
function html_decode(str)
{
var s = "";
if (str.length == 0) return "";
s = str.replace(/>/g, "&");
s = s.replace(/</g, "<");
s = s.replace(/>/g, ">");
s = s.replace(/ /g, " ");
s = s.replace(/'/g, "\'");
s = s.replace(/"/g, "\"");
s = s.replace(/<br>/g, "\n");
return s;
}