无情 发表于 2021-3-2 14:37

JavaScript过滤XSS

var filterXSS=function(oriStr){
    if(!oriStr){
      return oriStr;
    }
    var charCodes=['3c','3e','27','22','28','29','60',{format:'script{}',chr:'3a'}];//要转义字符的16进制ASCII码
    var xssChars=[],filterChars=[],tmpFormat='{}',tmpChr;
    for(var i=0;i<charCodes.length;i++){
      if('string'==typeof charCodes){
            tmpFormat='{}';
            tmpChr=charCodes;
      }else{
            tmpFormat=charCodes.format;
            tmpChr=charCodes.chr
      }
      xssChars.push(tmpFormat.replace('{}','\\u00'+tmpChr));
      xssChars.push(tmpFormat.replace('{}','%'+tmpChr));//1次encode
      xssChars.push(tmpFormat.replace('{}','%25'+tmpChr));//2次encode
      filterChars.push(tmpFormat.replace('{}','&#x'+tmpChr+';'));
      filterChars.push(tmpFormat.replace('{}','%26%23x'+tmpChr+'%3B'));//1次encode
      filterChars.push(tmpFormat.replace('{}','%2526%2523x' + tmpChr + '%253B'));//2次encode
    }
    for(var i=0;i<xssChars.length;i++){
      oriStr=oriStr.replace(new RegExp(xssChars,'gi'),filterChars);
    }
    //预防script:
    oriStr=oriStr.replace(/script[\u000d\u000a\u0020]+\:/,'script:');
    return oriStr;
}

顺睇帥 发表于 2021-3-2 14:38

谢谢分享!

meetyuan 发表于 2021-3-2 15:06


感谢分享,谢谢提供分享

loveless 发表于 2021-3-2 16:05

感谢楼主分享

immorta 发表于 2021-3-2 17:00

多谢分享多谢分享
页: [1]
查看完整版本: JavaScript过滤XSS