JavaScript过滤XSS

  1. var filterXSS=function(oriStr){
  2. if(!oriStr){
  3. return oriStr;
  4. }
  5. var charCodes=['3c','3e','27','22','28','29','60',{format:'script{}',chr:'3a'}];//要转义字符的16进制ASCII码[1< 2> 3' 4" 5( 6) 7`]
  6. var xssChars=[],filterChars=[],tmpFormat='{}',tmpChr;
  7. for(var i=0;i<charCodes.length;i++){
  8. if('string'==typeof charCodes[i]){
  9. tmpFormat='{}';
  10. tmpChr=charCodes[i];
  11. }else{
  12. tmpFormat=charCodes[i].format;
  13. tmpChr=charCodes[i].chr
  14. }
  15. xssChars.push(tmpFormat.replace('{}','\\u00'+tmpChr));
  16. xssChars.push(tmpFormat.replace('{}','%'+tmpChr));//1次encode
  17. xssChars.push(tmpFormat.replace('{}','%25'+tmpChr));//2次encode
  18. filterChars.push(tmpFormat.replace('{}','&#x'+tmpChr+';'));
  19. filterChars.push(tmpFormat.replace('{}','%26%23x'+tmpChr+'%3B'));//1次encode
  20. filterChars.push(tmpFormat.replace('{}','%2526%2523x' + tmpChr + '%253B'));//2次encode
  21. }
  22. for(var i=0;i<xssChars.length;i++){
  23. oriStr=oriStr.replace(new RegExp(xssChars[i],'gi'),filterChars[i]);
  24. }
  25. //预防script:
  26. oriStr=oriStr.replace(/script[\u000d\u000a\u0020]+\:/,'script:');
  27. return oriStr;
  28. }
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值