前端防御XSS

下面是前端过滤XSS的代码,取自于百度FEX前端团队的Ueditor在线编辑器:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
function xssCheck(str,reg){
     return str ? str.replace(reg || /[&<">'](?:(amp|lt|quot|gt|#39|nbsp|#\d+);)?/g, function (a, b) {
         if (b){
             return a;
         } else {
             return {
                 '<' : '&lt;' ,
                 '&' : '&amp;' ,
                 '"' : '&quot;' ,
                 '>' : '&gt;' ,
                 "'" :'&#39;',
             }[a]
         }
     }) : '' ;
}

然后我们在原有代码的基础上添加xssCheck()函数就行了。如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
<!DOCTYPE html>
< html >
< head >
     < meta charset = "utf-8" >
     < title >前端防御XSS#Demo1</ title >
</ head >
< body >
     < input type = "text" name = "xss" >
     < input type = "submit" value = "提交" id = "xssGet" >
</ body >
< script type = "text/javascript" src = "/Public/js/library/jquery.js" ></ script >
< script >
     $("#xssGet").click(function(){
         $.ajax({
             url: '/defenderXssTest_GetData.php',
             type: 'get',
             dataType: 'text',
             data: "xss="+$('input:first').val(),
             cache:false,
             async:false,
         })
         .done(function() {
             $.ajax({
                 url: '/defenderXssTest_QueryData.php',
                 type: 'post',
                 dataType: 'text',
                 cache:false,
                 async:false,
             })
             .done(function(data) {
                 $("body").append(xssCheck(data));
             })
         })
     });
     function xssCheck(str,reg){
         return str ? str.replace(reg || /[&<">'](?:(amp|lt|quot|gt|#39|nbsp|#\d+);)?/g, function (a, b) {
             if(b){
                 return a;
             }else{
                 return {
                     '<':'&lt;',
                     '&':'&amp;',
                     '"':'&quot;',
                     '>':'&gt;',
                     "'":'&#39;',
                 }[a]
             }
         }) : '';
     }
</ script >
</ html >

你可能感兴趣的:(前端防御XSS)