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>
  • 相关阅读:
    struts2之OGNL和struts2标签库和ValueStack对象
    struts2使用拦截器完成登陆显示用户信息操作和Struts2的国际化
    struts2的文件上传和文件下载
    jsp+servlet实现文件的上传和下载
    Ajax和JSON完成二级菜单联动的功能
    jxl的使用总结(java操作excel)
    Ajax异步验证登陆或者注册
    mydate97时间控件的使用
    Ckeditor一种很方便的文本编辑器
    搬家通知博文地址(将博客搬到CSDN)
  • 原文地址:https://www.cnblogs.com/frontendBY/p/5241243.html
Copyright © 2011-2022 走看看