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('<script>console.log("8");</script>'));
$("#box").html(filterXSS('<script>console.log("8");</script>'));//测试一下被转义成为了html实体,能否被输出
$("#box2").html(filterXSS('<script>console.log("8");</script>'));
//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);
页面输出:
控制台输出: