js 前端处理xss攻击,对危险的字符串进行过滤

es6:

npm install xss --save

这里测试使用的是es5,下载链接:

预防xss攻击,过滤标签.js_js过滤xss攻击-互联网文档类资源-CSDN下载

https://raw.githubusercontent.com/leizongmin/js-xss/master/dist/xss.js (过滤的比较严重,将html的所有属性都给过滤了)

调用函数:

function filterXSS(string)

html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div id="box"></div>
    <div id="box2"></div>
    <div id="box3"></div>
    <div id="box4"></div>
</body>
</html>
<script src="./xss.js"></script>
<script src="./jquery.3.2.1.min.js"></script>
<script src="./index2.js"></script>

js:

//如果出现在标签属性中会被过滤掉,出现在文本中不会被过滤
//所有事件:error|mousewheel|mouseover|click|load|onload|submit|focus|blur|start

//onclick
console.log(1,filterXSS('<a href="#" onclick="alert(/xss/)">click me</a>'));
console.log(2,filterXSS('<a>onclick</a>'));
console.log(3,filterXSS('<a onclick="console.log(88)">onclick</a>'));
//script
console.log(4,filterXSS('<script>console.log("8");</script>'));
console.log(5,filterXSS('&lt;script&gt;console.log("8");&lt;/script&gt;'));
$("#box").html(filterXSS('<script>console.log("8");</script>'));//测试一下被转义成为了html实体,能否被输出
$("#box2").html(filterXSS('&lt;script&gt;console.log("8");&lt;/script&gt;'));
//onerror
console.log(6,filterXSS('<img src="./pull_black_blue.png" width="45" onerror="console.log(5);"/>'));//图片的onerror被过滤掉
$("#box3").html(filterXSS('<img src="./pull_black_blue.png" width="45" onerror="console.log(5);"/>'));
//onblur
console.log(7,filterXSS('<a onblur="console.log(88)">onclick</a>'));
//javascript
console.log(8,filterXSS('<img src="javascript:alert("xss");"/>'));
var a=filterXSS("<span class='box' style='width:30px;'></span>");
console.log(9,a);
$("#box4").html(a);

页面输出:

控制台输出:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

草字

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值