zoukankan      html  css  js  c++  java
  • 前端防御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>
  • 相关阅读:
    Java内存区域
    spring学习之Bean
    记一次日本公司的Java面试
    java中打印输出数组内容的三种方式
    Java创建子类时构造器执行顺序
    转发&重定向
    Java继承
    GXOI&GZOI
    LCT能干啥???
    后缀自动机的一些应用
  • 原文地址:https://www.cnblogs.com/frontendBY/p/5241243.html
Copyright © 2011-2022 走看看