2

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?

2
  • encodeURI() will not encode: ~!@#$&*()=:/,;?+' encodeURIComponent() will not encode: ~!*()' now you decide! . But can you really trust client side? Commented Nov 25, 2016 at 15:03
  • 1
    For XSS Sanitization have a look at Yahoo's xss-filters library or at DOMPurify. Commented Nov 25, 2016 at 15:08

2 Answers 2

3

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>

Sign up to request clarification or add additional context in comments.

5 Comments

I used var isValid = ($('input').val().indexOf('<script'>') >-1) ? false : true; Can I?
Don't think so.. Suppose as one example that someone writes: <script type="text/javascript">alert('hi')</script>
I know, so just indexOf('script')
If someone type: "I would like to make a new script"??
then it will be invalid :P
2

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>

1 Comment

It changes characters also, not desired.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.