Josh-CO Dev

Solving the worlds problems one line of code at a time.

Another basic way to defend against XSS attacks

Leave a comment

Another mediocre way to defend against XSS attacks is to encode or “escape” any input before allowing it to be handled by the interpreter. Here is a basic example of how to handle this in JavaScript. Use the same html as our previous example, then just paste this functions into your scripts.js file and rename the submit button to correspond to the event handler.

    $("#btnSubmit3").click(function () {

        var htmlToRender = "Welcome to our site " + escape($("#inputName").val());


This will strip out any special character so that they are not handled by the interpreter. In the below example, I tried to enter the following code:


And this was the result


Before, we saw that this actually caused an alert box to pop up on the screen. Making this one simple change allowed the statement to be ignored altogether.

Much like our previous defense example, this will not give you defense in depth, but it will give you a basic level of security that you may have never even thought you needed.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s