Search code examples
javascripthtmlgrailsbackbone.jsxss

How to encodeAsHtml in a javascript file in a grails project


I have a grails project with the UI mostly implemented in javascript(BackBone.js). Briefly speaking i have a gsp file that includes a javascript file. The events of the gsp page are handled by the handlers defined in the Javascript file.

Now i have some DOM XSS violations in the javascript file. eg. cell1.innerHTML = '<div name="caCertFileName">' + item.fileName.substring(33) + '</div>';

Now i cannot understand how to use the encodeAsHTML / encodeAsJavascript funtions in the javascript file. I need a short example to figure this out.


Solution

  • You can define JavaScript function to do html escaping, and use it like:

    cell1.innerHTML = '<div name="caCertFileName">' + encodeHtml(item.fileName.substring(33)) + '</div>';

    With a function like encodeHtml that converts characters like < to &lt;, and the data being inserted between tags and not inside them, this can work.

    See: Can I escape html special chars in javascript? for implementations.

    You may be better off avoiding innerHTML though, and using the DOM manipulation functions. With jQuery for example you can write:

    $(cell1).append($("<div>")
        .attr("name", "caCertFileName")
        .text(item.fileName.substring(33)));
    

    This keeps a separation between the HTML structure and user data.