需求是模板字符串中不允许出现<script> 标签、不允许有javascript: 和 .js 文件引用,主要方法如下:
clearScriptTag (str) {
const reg = /<script[^>]*>([\S\s]*?)<\/script>/gim;
// 清除标签内 相关 xss 安全代码
const reg1 = /javascript:/gim;
const reg2 = / *.js/gim;
if (reg.test(str)) {
str = str.replace(reg, '');
this.$message.error('非法标签 <script> 已被替换为空');
}
if (reg1.test(str)) {
str = str.replace(reg1, '');
this.$message({
message: '非法代码javascript:已被替换为空',
type: 'error',
offset: 60
});
}
if (reg2.test(str)) {
str = str.replace(reg2, '');
this.$message({
message: '非法*.js已被替换为空',
type: 'error',
offset: 100
});
}
return str;
},
测试:
// 输入字符串为:
let str = '<div>
<span>测试文字</span>
</div>
<script>asdfasdfs</script>
<script></script>
<a></a>
<script>asdfasdfs sdf234 asd fasdfs</script>
<script>asdfasdfs sdf234 asd fa
sdfs</script>
<span src:"javascript:aaa//xx.js">测试文字</span>
<span src:"javascript:aaa//xaaax.js">测试文字</span>
<span src:"javascript:aaa//xx.js">javascript:aaa//xx.js</span>'
// 过滤后字符串为:
'<div>
<span>测试文字</span>
</div>
<a></a>
<span src:"aaa//xx">测试文字</span>
<span src:"aaa//xaaax">测试文字</span>
<span src:"aaa//xx">aaa//xx</span>'