Book Image

JavaScript Security

By : Eugene Liang
Book Image

JavaScript Security

By: Eugene Liang

Overview of this book

Table of Contents (13 chapters)

Defending against cross-site scripting


We will go through the basic techniques of defending against cross-site scripting. This is by no means a comprehensive list of defenses against cross-site scripting, but it should be enough to get you started.

Do not trust users – parsing input by users

We can parse the user's input using various techniques. Since we are talking about JavaScript in this book, we can apply the following JavaScript function to prevent the execution of malicious code:

    function htmlEntities(str) {
        return String(str).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
    }

This function effectively strips the malicious code from the user's input and output as normal strings. To see this function in action, simply refer to the source code for this chapter. You can find this function in use at python_server/templates/todos_secure.html. For ease of reference, the code snippet is being applied here as...