Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dojo Toolkit: how to escape an HTML string?

A user of my HTML 5 application can enter his name in a form, and this name will be displayed elsewhere. More specifically, it will become the innerHTML of some HTML element.

The problem is that this can be exploited if one enters valid HTML markup in the form, i.e. some sort of HTML injection, if you will.

The user's name is only stored and displayed on the client side so in the end the user himself is the only one who is affected, but it's still sloppy.

Is there a way to escape a string before I put it in an elements innerHTML in Dojo? I guess that Dojo at one point did in fact have such a function (dojo.string.escape()) but it doesn't exist in version 1.7.

Thanks.

like image 614
Jan Van den bosch Avatar asked Mar 28 '12 08:03

Jan Van den bosch


People also ask

What is escape HTML?

HTML escaping is used to represent special characters in HTML code. For example, < less than symbol > has a special meaning in HTML markup language. This tool will convert a string to HTML entities or convert HTML entities to plain text.

What is Dojo in HTML?

dojo/html is a module that provides a single public function set() . It is used to safely and conveniently replace an element's content, while providing some hooks and options for how the replacement should be handled.


1 Answers

As of Dojo 1.10, the escape function is still part of the string module.

http://dojotoolkit.org/api/?qs=1.10/dojo/string

Here's how you can use it as a simple template system.

require([
    'dojo/string'
], function(
    string
){
    var template = '<h1>${title}</h1>';
    var message = {title: 'Hello World!<script>alert("Doing something naughty here...")</script>'}
    var html = string.substitute(
        template
        , message
        , string.escape
    );
});
like image 150
Richard Ayotte Avatar answered Sep 23 '22 04:09

Richard Ayotte