Is there a way to sanitize or scape strings to secure put data in a object into script or DOM like:

var myObj = JSON.parse({someObject: value})
someElement.innerHTML('<div data-id="'+myObj.someObject+'">' + '+myObj.someObject+')?

This JSON is generated when an user A sends a object inside a JSON to user B, in a chat application that user B receives that JSON and stores this object in a array then generates an HTML element with an attribute and content.


1 Answer 1


Some of the points that you should take care are: (in no order)

  1. Untrusted user input should only be treated as displayable text. Never treat untrusted data as code or markup within JavaScript code. HTML encode all user input.
  2. Always JavaScript encode and delimit untrusted data as quoted strings when entering the application
  3. Avoid use of HTML rendering methods

  4. Use document.createElement("..."), element.setAttribute("...","value"), element.appendChild(...), etc. to build dynamic interfaces. Dangerous attributes include any attribute that is a command execution context, such as onclick or onblur.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .