According to OWASP, to make dynamic updates to HTML in the DOM safe, we recommend
- HTML encoding, and then
- JavaScript encoding all untrusted input, as shown in
these examples:
element.innerHTML = “<%=Encoder.encodeForJS(Encoder.encodeForHTML(untrustedData))%>”;
There is a web application where the servlet receives the user input(received as an AJAX request) ,process the data and sends a text response which is used to change the DOM dynamically by setting the value of an element(using document.getElementById("elementID").innerHTML = data;).
To prevent DOM based XSS is it required to escape the HTML and JavaScript using the ESAPI encoder as
String htmlEscapedStr=ESAPI.encoder().encodeForHTML(content);
String JSEscapedStr=ESAPI.encoder().encodeForJavaScript(htmlEscapedStr);
response.setContentType("text/plain");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(JSEscapedStr);
;
or is it safe to write the unencoded String to the stream
response.setContentType("text/plain");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(content);