Duplicated Duplicated - 5 months ago 17
jQuery Question

Javascript XSS Validation

I have a javascript / jquery code for searching and i tested inserting a script tag with an alert and i found out that my search was vulnerable to an XSS. May i ask if is there a way to filter the search?

Here is my code.

$('#search').keyup(function(e){
if($.trim($(this).val()) != ''){
$.get("php/api.php",{"function":"Searching","search": $(this).val() },function(e){
$('#search-result').html(e);
});
$('#search-result').show();
if(e.which == 13) {
location.href = 'search.php?result='+$(this).val();
}
}else{
$('#search-result').html("");
}
});

Answer

To remove the script tag from user input you can use the below function

 function stripScripts(s) {
    var div = document.createElement('div');
    div.innerHTML = s;
    var scripts = div.getElementsByTagName('script');
    var i = scripts.length;
    while (i--) {
      scripts[i].parentNode.removeChild(scripts[i]);
    }
    return div.innerHTML;
  }

 stripScripts('<span><script type="text/javascript">alert(\'foo\');<\/script><\/span>')

But thats going to prevent only a specfic type of XSS. Check this link for more details.

Comments