Jessie Emerson
Jessie Emerson

Reputation: 743

sanitize user input on client side using javascript

I'm already handle the sanitization in my server side, any improper input text like <script>alert('hi')</script> can be handle properly. But because I also pass around data using websocket, so this part is broken if user send

<script>alert('hi')</script>

I found encodeURIComponent but confused with encodeURI, which one is for xss handling in client side?

Upvotes: 2

Views: 17317

Answers (2)

TheRealSuicune
TheRealSuicune

Reputation: 367

If you're using HTML, then you can convert every character to entities.

function sanitize(a) {
  var b = "";
  for (var i = 0; i < a.length; i++) {
    b += "&#x"+a.charCodeAt(i).toString(16)+";"
  }
  return b;
}
User Input:
<input type="textbox" id="box">
<input type="button" value="Sanitize to entities" onclick="document.getElementById('sanitizedfield').innerText=(sanitize(document.getElementById('box').value))"><pre id="sanitizedfield"></pre>

Upvotes: 2

Yosvel Quintero
Yosvel Quintero

Reputation: 19060

For XSS Sanitization have a look at Yahoo's xss-filters library or at DOMPurify.

Here an example using DOMPurify:

var input = document.getElementById('input'),
    result = document.getElementById('result'),
    button = document.getElementById('button').addEventListener('click', function(){
      // Sanitize
      var clean = DOMPurify.sanitize(input.value, {SAFE_FOR_TEMPLATES: true});

      result.innerHTML = clean;
      console.log(clean);
    });
<script src="https://cdnjs.cloudflare.com/ajax/libs/dompurify/0.8.4/purify.min.js"></script>

<input type="text" id="input"> 
<button id="button">Send</button>
<p id="result"></p>

Upvotes: 3

Related Questions