前言
上个月写了一个老项目,用的语言是JQ,项目在测试的时候,遇到了测试人员的前端语言注入,在表单内容里输入了带有html标签的字符内容,导致列表崩溃。至今记忆尤深,今天看文章的时候看到了腾讯的这个方法,又重新写了一个demo。
核心方法
function htmlEncode(iStr) {
let sStr = iStr;
sStr = sStr.replace(/&/g, "&");
sStr = sStr.replace(/>/g, ">");
sStr = sStr.replace(/</g, "<");
sStr = sStr.replace(/"/g, """);
sStr = sStr.replace(/'/g, "'");
return sStr;
}
该方法来自于腾讯的JavaScript安全指南。
使用方法
const text = htmlEncode(value)
value:需要转换的字符串
Demo
效果
HTML
<div class="content">
<h3>新增表单</h3>
<input id="a" type="text">
<button type="submit" onclick="start()">保存</button>
<p class="line"></p>
<h3>列表</h3>
<div id="list">
<div class="box">
<p>展示输入的数据</p>
</div>
<div class="box">
<p>看看有没有影响</p>
</div>
</div>
<button onclick="clearList()">清空</button>
</div>
JS
<script>
function start() {
const a = document.getElementById('a')
const text = htmlEncode(a.value)
const list=document.getElementById('list')
let html=''
html=`
<div class="box">
<p>展示输入的数据</p>
<p>${text}</p>
</div>
<div class="box">
<p>看看有没有影响</p>
</div>`
list.innerHTML=html
}
function htmlEncode(iStr) {
let sStr = iStr;
sStr = sStr.replace(/&/g, "&");
sStr = sStr.replace(/>/g, ">");
sStr = sStr.replace(/</g, "<");
sStr = sStr.replace(/"/g, """);
sStr = sStr.replace(/'/g, "'");
return sStr;
}
function clearList(){
const list=document.getElementById('list')
list.innerHTML=''
}
</script>
CSS
<style>
.content {
width: 500px;
margin: auto;
border: 1px solid #ebeef5;
box-shadow: 0 2px 12px 0 rgba(0, 0, 0, .1);
text-align: center;
border-radius: 4px;
height: 1000px;
overflow: auto;
}
input {
border: 1px solid #ebeef5;
padding: 7px 10px;
border-radius: 4px;
outline: none;
}
button {
border: 1px solid #ebeef5;
padding: 5px 10px;
border-radius: 4px;
margin-right: 10px;
color: #fff;
background-color: #409eff;
border-color: #409eff;
}
.line{
margin: 20px auto;
border: 1px solid #ebeef5;
box-shadow: 0 2px 12px 0 rgba(0, 0, 0, .1);
}
.list{
text-align: center;
}
.box {
width: 300px;
height: 300px;
box-shadow: 0 2px 12px 0 rgba(0, 0, 0, .1);
text-align: center;
line-height: 30px;
border-radius: 4px;
border: 1px solid #ebeef5;
background-color: #fff;
overflow: hidden;
color: #303133;
transition: .3s;
letter-spacing: 3px;
margin: 10px auto;
}
</style>