655

Does anyone know of an easy way to escape HTML from strings in jQuery? I need to be able to pass an arbitrary string and have it properly escaped for display in an HTML page (preventing JavaScript/HTML injection attacks). I'm sure it's possible to extend jQuery to do this, but I don't know enough about the framework at the moment to accomplish this.

Matt Fenwick
  • 48,199
  • 22
  • 128
  • 192
Page
  • 9,945
  • 5
  • 37
  • 45

27 Answers27

662

There is also the solution from mustache.js

var entityMap = {
  '&': '&',
  '<': '&lt;',
  '>': '&gt;',
  '"': '&quot;',
  "'": '&#39;',
  '/': '&#x2F;',
  '`': '&#x60;',
  '=': '&#x3D;'
};

function escapeHtml (string) {
  return String(string).replace(/[&<>"'`=\/]/g, function (s) {
    return entityMap[s];
  });
}
Hardik Modha
  • 12,098
  • 3
  • 36
  • 40
Tom Gruner
  • 9,635
  • 1
  • 20
  • 26
  • Sorry to bother but is there anyway this can be reversed? i don't know regex so i need help – Tony Patino Jan 29 '22 at 09:03
  • it would be handy if there were unit tests for this, but this seems like a better solution – spy Dec 11 '22 at 14:09
  • What if the string is already escaped? This expression matches `&` except when it's followed by ( 1-8 letters followed by 0-2 digits OR `#` followed by a 1-4 (decimal OR hex) digit number ) followed by `;`. Pattern: ``/([<>"'`=\/]|&(?!([a-zA-Z]{1,8}\d{0,2}|#(\d{1,4}|x[a-zA-Z\d]{1,4}));))/g`` Use: ``escapeHtml('"This" = a &v3ry; &dumb; quote.')`` Result: ``'"This" = a &v3ry; &dumb; quote.'`` In DOM: ``'"This"\t=\ta &v3ry; &dumb; quote.'`` Page display: ``"This" = a &v3ry; &dumb; quote.`` – Travis Bemrose Feb 09 '23 at 16:26
485

Since you're using jQuery, you can just set the element's text property:

// before:
// <div class="someClass">text</div>
var someHtmlString = "<script>alert('hi!');</script>";

// set a DIV's text:
$("div.someClass").text(someHtmlString);
// after: 
// <div class="someClass">&lt;script&gt;alert('hi!');&lt;/script&gt;</div>

// get the text in a string:
var escaped = $("<div>").text(someHtmlString).html();
// value: 
// &lt;script&gt;alert('hi!');&lt;/script&gt;
Aliaksandr Sushkevich
  • 11,550
  • 7
  • 37
  • 44
travis
  • 35,751
  • 21
  • 71
  • 94
  • 1
    Is it safe ? https://www.linkedin.com/pulse/htmlencode-htmldecode-jquery-roman-x-shafigullin/ – paaacman Jan 18 '22 at 13:41
  • @paaacman setting the property with jQuery using `.text()` or `.attr()` is safe, but building an HTML string like in that example you would definitely run into issues. – travis Jan 19 '22 at 18:16
185
$('<div/>').text('This is fun & stuff').html(); // "This is fun &amp; stuff"

Source: http://debuggable.com/posts/encode-html-entities-with-jquery:480f4dd6-13cc-4ce9-8071-4710cbdd56cb

Edward
  • 3,292
  • 1
  • 27
  • 38
Henrik N
  • 15,786
  • 5
  • 82
  • 131
61

If you're escaping for HTML, there are only three that I can think of that would be really necessary:

html.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");

Depending on your use case, you might also need to do things like " to &quot;. If the list got big enough, I'd just use an array:

var escaped = html;
var findReplace = [[/&/g, "&amp;"], [/</g, "&lt;"], [/>/g, "&gt;"], [/"/g, "&quot;"]]
for(var item in findReplace)
    escaped = escaped.replace(findReplace[item][0], findReplace[item][1]);

encodeURIComponent() will only escape it for URLs, not for HTML.

Alexander Elgin
  • 6,796
  • 4
  • 40
  • 50
tghw
  • 25,208
  • 13
  • 70
  • 96
  • 14
    This regular expression will produce strange results if the HTML in question already has escaped entities. For example, escaping "Tom & Jerry" will produce "Tom &amp; Jerry" – Ryan Nov 07 '10 at 18:24
  • 12
    Please use `var` to declare `item` locally; anyway, don't use a `for … in` loop at all when looping through an array! Use an ordinary `for` loop instead. Oh, and it's `encodeURIComponent`, not `escapeURIComponent`. – Marcel Korpel Mar 16 '11 at 16:33
  • 3
    If you are working with tag attributes, then you will also need to escape quotes and/or double quotes. The PHP documentation for htmlspecialchars contains a useful list of conversions that it performs. http://www.php.net/htmlspecialchars – geofflee Mar 24 '11 at 12:05
  • 4
    Just a kind reminder for new people, don't use this if you intend to have non-english characters somewhere on your website ... Obviously this won't do because of characters with accents like 'é' : `&eacute`; Here's a list of html entities, for reference : http://www.w3schools.com/tags/ref_entities.asp – LoganWolfer Apr 01 '11 at 21:50
  • 1
    In general, reinventing the wheel for stuff like this is a bad idea... there are just so many gotchas involved. – bchurchill Feb 10 '13 at 02:20
  • 12
    @Ryan: While it's worth pointing out that this solution doesn't handle already-encoded strings correctly, it's also worth nothing that the same applies to most - possibly all - solutions on this page. – mklement0 Apr 12 '13 at 14:21
  • 1
    @Ryan there's a simple solution to the double encoding issue. Just unescape the string before escaping it. The unescape call will be a NOOP if the string doesn't already include encoded entities. – Ryan Mohr Feb 27 '14 at 18:48
  • 2
    @RyanMohr You say that escaping "Tom & Jerry" will produce "Tom &amp; Jerry". Good! That's exactly the correct behaviour. Correct escaping like this lets people post comments like yours which discuss HTML without weird things happening. If it stayed the same, *that* would be weird. – Flimm Jun 21 '19 at 15:27
  • @LoganWolfer dead link – spy Dec 11 '22 at 14:13
  • 1
    @spy https://html.spec.whatwg.org/multipage/named-characters.html#named-character-references – tghw Dec 13 '22 at 20:59
42

Easy enough to use underscore:

_.escape(string) 

Underscore is a utility library that provides a lot of features that native js doesn't provide. There's also lodash which is the same API as underscore but was rewritten to be more performant.

chovy
  • 72,281
  • 52
  • 227
  • 295
39

I wrote a tiny little function which does this. It only escapes ", &, < and > (but usually that's all you need anyway). It is slightly more elegant then the earlier proposed solutions in that it only uses one .replace() to do all the conversion. (EDIT 2: Reduced code complexity making the function even smaller and neater, if you're curious about the original code see end of this answer.)

function escapeHtml(text) {
    'use strict';
    return text.replace(/[\"&<>]/g, function (a) {
        return { '"': '&quot;', '&': '&amp;', '<': '&lt;', '>': '&gt;' }[a];
    });
}

This is plain Javascript, no jQuery used.

Escaping / and ' too

Edit in response to mklement's comment.

The above function can easily be expanded to include any character. To specify more characters to escape, simply insert them both in the character class in the regular expression (i.e. inside the /[...]/g) and as an entry in the chr object. (EDIT 2: Shortened this function too, in the same way.)

function escapeHtml(text) {
    'use strict';
    return text.replace(/[\"&'\/<>]/g, function (a) {
        return {
            '"': '&quot;', '&': '&amp;', "'": '&#39;',
            '/': '&#47;',  '<': '&lt;',  '>': '&gt;'
        }[a];
    });
}

Note the above use of &#39; for apostrophe (the symbolic entity &apos; might have been used instead – it is defined in XML, but was originally not included in the HTML spec and might therefore not be supported by all browsers. See: Wikipedia article on HTML character encodings). I also recall reading somewhere that using decimal entities is more widely supported than using hexadecimal, but I can't seem to find the source for that now though. (And there cannot be many browsers out there which does not support the hexadecimal entities.)

Note: Adding / and ' to the list of escaped characters isn't all that useful, since they do not have any special meaning in HTML and do not need to be escaped.

Original escapeHtml Function

EDIT 2: The original function used a variable (chr) to store the object needed for the .replace() callback. This variable also needed an extra anonymous function to scope it, making the function (needlessly) a little bit bigger and more complex.

var escapeHtml = (function () {
    'use strict';
    var chr = { '"': '&quot;', '&': '&amp;', '<': '&lt;', '>': '&gt;' };
    return function (text) {
        return text.replace(/[\"&<>]/g, function (a) { return chr[a]; });
    };
}());

I haven't tested which of the two versions are faster. If you do, feel free to add info and links about it here.

zrajm
  • 1,361
  • 1
  • 12
  • 21
37

I realize how late I am to this party, but I have a very easy solution that does not require jQuery.

escaped = new Option(unescaped).innerHTML;

Edit: This does not escape quotes. The only case where quotes would need to be escaped is if the content is going to be pasted inline to an attribute within an HTML string. It is hard for me to imagine a case where doing this would be good design.

Edit 3: For the fastest solution, check the answer above from Saram. This one is the shortest.

Adam Leggett
  • 3,714
  • 30
  • 24
32

Here is a clean, clear JavaScript function. It will escape text such as "a few < many" into "a few &lt; many".

function escapeHtmlEntities (str) {
  if (typeof jQuery !== 'undefined') {
    // Create an empty div to use as a container,
    // then put the raw text in and get the HTML
    // equivalent out.
    return jQuery('<div/>').text(str).html();
  }

  // No jQuery, so use string replace.
  return str
    .replace(/&/g, '&amp;')
    .replace(/>/g, '&gt;')
    .replace(/</g, '&lt;')
    .replace(/"/g, '&quot;')
    .replace(/'/g, '&apos;');
}
intrepidis
  • 2,870
  • 1
  • 34
  • 36
32

After last tests I can recommend fastest and completely cross browser compatible native javaScript (DOM) solution:

function HTMLescape(html){
    return document.createElement('div')
        .appendChild(document.createTextNode(html))
        .parentNode
        .innerHTML
}

If you repeat it many times you can do it with once prepared variables:

//prepare variables
var DOMtext = document.createTextNode("test");
var DOMnative = document.createElement("span");
DOMnative.appendChild(DOMtext);

//main work for each case
function HTMLescape(html){
  DOMtext.nodeValue = html;
  return DOMnative.innerHTML
}

Look at my final performance comparison (stack question).

Aliaksandr Sushkevich
  • 11,550
  • 7
  • 37
  • 44
Saram
  • 1,500
  • 1
  • 18
  • 35
  • 2
    Is it necessary to use two nodes? How about just one: `var p = document.createElement('p'); p.textContent = html; return p.innerHTML;` – Dan Dascalescu Aug 13 '15 at 15:14
  • 2
    @DanDascalescu: According to [MDN](https://developer.mozilla.org/en-US/docs/Web/API/Node/textContent), the `textContent` function is only supported by Chrome 1+, Firefox 2, IE9, Opera 9.64 and Safari 3 (the latter two annotated "possibly earlier"). It would thus break the OPs "completely cross-browser compatible" claim. – zb226 Nov 11 '15 at 11:00
  • `p.innerText = html; return p.innerHTML` – Bekim Bacaj Nov 27 '16 at 08:58
24

Try Underscore.string lib, it works with jQuery.

_.str.escapeHTML('<div>Blah blah blah</div>')

output:

'&lt;div&gt;Blah blah blah&lt;/div&gt;'
Nikita Koksharov
  • 10,283
  • 1
  • 62
  • 71
18

escape() and unescape() are intended to encode / decode strings for URLs, not HTML.

Actually, I use the following snippet to do the trick that doesn't require any framework:

var escapedHtml = html.replace(/&/g, '&amp;')
                      .replace(/>/g, '&gt;')
                      .replace(/</g, '&lt;')
                      .replace(/"/g, '&quot;')
                      .replace(/'/g, '&apos;');
Alexander Elgin
  • 6,796
  • 4
  • 40
  • 50
NicolasBernier
  • 1,586
  • 14
  • 15
  • If you're going to have `"`s then you need to add at least `'` and `\` to the fray. Those are only really needed for string tag data inside elements in html. For html data itself (outside tags) only the first 3 are required. – Marius Jul 12 '13 at 12:01
15

I've enhanced the mustache.js example adding the escapeHTML() method to the string object.

var __entityMap = {
    "&": "&amp;",
    "<": "&lt;",
    ">": "&gt;",
    '"': '&quot;',
    "'": '&#39;',
    "/": '&#x2F;'
};

String.prototype.escapeHTML = function() {
    return String(this).replace(/[&<>"'\/]/g, function (s) {
        return __entityMap[s];
    });
}

That way it is quite easy to use "Some <text>, more Text&Text".escapeHTML()

Jeena
  • 2,172
  • 3
  • 27
  • 46
  • Useful, but also I moved `__entityMap` into function local scope. And wrapped all of this into `if (typeof String.prototype.escapeHTML !== 'function'){...}` – FlameStorm Aug 09 '17 at 11:27
11

If you have underscore.js, use _.escape (more efficient than the jQuery method posted above):

_.escape('Curly, Larry & Moe'); // returns: Curly, Larry &amp; Moe
Alexander Elgin
  • 6,796
  • 4
  • 40
  • 50
ronnbot
  • 1,241
  • 1
  • 9
  • 5
5

This is a nice safe example...

function escapeHtml(str) {
    if (typeof(str) == "string"){
        try{
            var newStr = "";
            var nextCode = 0;
            for (var i = 0;i < str.length;i++){
                nextCode = str.charCodeAt(i);
                if (nextCode > 0 && nextCode < 128){
                    newStr += "&#"+nextCode+";";
                }
                else{
                    newStr += "?";
                }
             }
             return newStr;
        }
        catch(err){
        }
    }
    else{
        return str;
    }
}
user427969
  • 3,836
  • 6
  • 50
  • 75
amrp
  • 59
  • 1
  • 1
5

If your're going the regex route, there's an error in tghw's example above.

<!-- WON'T WORK -  item[0] is an index, not an item -->

var escaped = html; 
var findReplace = [[/&/g, "&amp;"], [/</g, "&lt;"], [/>/g,"&gt;"], [/"/g,
"&quot;"]]

for(var item in findReplace) {
     escaped = escaped.replace(item[0], item[1]);   
}


<!-- WORKS - findReplace[item[]] correctly references contents -->

var escaped = html;
var findReplace = [[/&/g, "&amp;"], [/</g, "&lt;"], [/>/g, "&gt;"], [/"/g, "&quot;"]]

for(var item in findReplace) {
     escaped = escaped.replace(findReplace[item[0]], findReplace[item[1]]);
}
Wayne
  • 501
  • 6
  • 7
  • 2
    I believe it should be for(var item in findReplace) { escaped = escaped.replace(findReplace[item][0], findReplace[item][1]); } – Chris Stephens Jun 23 '11 at 21:23
3

You can easily do it with vanilla js.

Simply add a text node the document. It will be escaped by the browser.

var escaped = document.createTextNode("<HTML TO/ESCAPE/>")
document.getElementById("[PARENT_NODE]").appendChild(escaped)
raam86
  • 6,785
  • 2
  • 31
  • 46
3

2 simple methods that require NO JQUERY...

You can encode all characters in your string like this:

function encode(e){return e.replace(/[^]/g,function(e){return"&#"+e.charCodeAt(0)+";"})}

Or just target the main characters to worry about &, line breaks, <, >, " and ' like:

function encode(r){
return r.replace(/[\x26\x0A\<>'"]/g,function(r){return"&#"+r.charCodeAt(0)+";"})
}

var myString='Encode HTML entities!\n"Safe" escape <script></'+'script> & other tags!';

test.value=encode(myString);

testing.innerHTML=encode(myString);

/*************
* \x26 is &ampersand (it has to be first),
* \x0A is newline,
*************/
<p><b>What JavaScript Generated:</b></p>

<textarea id=test rows="3" cols="55"></textarea>

<p><b>What It Renders Too In HTML:</b></p>

<div id="testing">www.WHAK.com</div>
Alexander Elgin
  • 6,796
  • 4
  • 40
  • 50
Dave Brown
  • 923
  • 9
  • 6
3

Plain JavaScript escaping example:

function escapeHtml(text) {
    var div = document.createElement('div');
    div.innerText = text;
    return div.innerHTML;
}

escapeHtml("<script>alert('hi!');</script>")
// "&lt;script&gt;alert('hi!');&lt;/script&gt;"
iamandrewluca
  • 3,411
  • 1
  • 31
  • 38
  • 3
    Code-only answers are discouraged because they do not explain how they resolve the issue. Please update your answer to explain *how this improves on the other accepted and upvoted answers* this question already has. Also, this question is 9 years old, your efforts would be more appreciated by users who have recent unanswered questions. Please review [How do I write a good answer](https://stackoverflow.com/help/how-to-answer). – FluffyKitten Oct 11 '17 at 10:20
  • 1
    @FluffyKitten here is an an extremely nicly written blog post on the advantages and disadvantages of such function that explains in detail everything you would like to know :) http://shebang.brandonmintern.com/foolproof-html-escaping-in-javascript/ – db306 Nov 13 '17 at 07:54
  • @db306 The answer was flagged as low quality because code-only answer don't meet Stack Overflow guidelines - see [How to write a good answer](https://stackoverflow.com/help/how-to-answer). My comment was added during the review process to explain what is required to improve it, i.e. the answer needs to by updated to explain what the code does and how it improves on the existing answers. The upvotes are from other reviewers to endorse this. Adding an external link to the comments still does not meet SO guidelines. Instead Andrew needs to include the relevant information directly in his answer. – FluffyKitten Nov 14 '17 at 09:19
  • Note that brandonmintern DOT com expired and is now parked. The new shebang address is shebang.mintern.net/foolproof-html-escaping-in-javascript/. – Brandon Apr 24 '20 at 18:52
2
(function(undefined){
    var charsToReplace = {
        '&': '&amp;',
        '<': '&lt;',
        '>': '&gt;'
    };

    var replaceReg = new RegExp("[" + Object.keys(charsToReplace).join("") + "]", "g");
    var replaceFn = function(tag){ return charsToReplace[tag] || tag; };

    var replaceRegF = function(replaceMap) {
        return (new RegExp("[" + Object.keys(charsToReplace).concat(Object.keys(replaceMap)).join("") + "]", "gi"));
    };
    var replaceFnF = function(replaceMap) {
        return function(tag){ return replaceMap[tag] || charsToReplace[tag] || tag; };
    };

    String.prototype.htmlEscape = function(replaceMap) {
        if (replaceMap === undefined) return this.replace(replaceReg, replaceFn);
        return this.replace(replaceRegF(replaceMap), replaceFnF(replaceMap));
    };
})();

No global variables, some memory optimization. Usage:

"some<tag>and&symbol©".htmlEscape({'©': '&copy;'})

result is:

"some&lt;tag&gt;and&amp;symbol&copy;"
Gheljenor
  • 362
  • 3
  • 3
2

ES6 one liner for the solution from mustache.js

const escapeHTML = str => (str+'').replace(/[&<>"'`=\/]/g, s => ({'&': '&amp;','<': '&lt;','>': '&gt;','"': '&quot;',"'": '&#39;','/': '&#x2F;','`': '&#x60;','=': '&#x3D;'})[s]);
chickens
  • 19,976
  • 6
  • 58
  • 55
1
function htmlDecode(t){
   if (t) return $('<div />').html(t).text();
}

works like a charm

d-_-b
  • 21,536
  • 40
  • 150
  • 256
0
function htmlEscape(str) {
    var stringval="";
    $.each(str, function (i, element) {
        alert(element);
        stringval += element
            .replace(/&/g, '&amp;')
            .replace(/"/g, '&quot;')
            .replace(/'/g, '&#39;')
            .replace(/</g, '&lt;')
            .replace(/>/g, '&gt;')
            .replace(' ', '-')
            .replace('?', '-')
            .replace(':', '-')
            .replace('|', '-')
            .replace('.', '-');
    });
    alert(stringval);
    return String(stringval);
}
Shadow The GPT Wizard
  • 66,030
  • 26
  • 140
  • 208
0

A speed-optimized version:

function escapeHtml(s) {
   let out = "";
   let p2 = 0;
   for (let p = 0; p < s.length; p++) {
      let r;
      switch (s.charCodeAt(p)) {
         case 34: r = "&quot;"; break;  // "
         case 38: r = "&amp;" ; break;  // &
         case 39: r = "&#39;" ; break;  // '
         case 60: r = '&lt;'  ; break;  // <
         case 62: r = '&gt;'  ; break;  // >
         default: continue;
      }
      if (p2 < p) {
         out += s.substring(p2, p);
      }
      out += r;
      p2 = p + 1;
   }
   if (p2 == 0) {
      return s;
   }
   if (p2 < s.length) {
      out += s.substring(p2);
   }
   return out;
}

const s = "Hello <World>!";
document.write(escapeHtml(s));
console.log(escapeHtml(s));
Christian d'Heureuse
  • 5,090
  • 1
  • 32
  • 28
0

For escape html specials (UTF-8)

function htmlEscape(str) {
  return str
      .replace(/&/g, '&amp;')
      .replace(/"/g, '&quot;')
      .replace(/'/g, '&#39;')
      .replace(/</g, '&lt;')
      .replace(/>/g, '&gt;')
      .replace(/\//g, '&#x2F;')
      .replace(/=/g,  '&#x3D;')
      .replace(/`/g, '&#x60;');
}

For unescape html specials (UTF-8)

function htmlUnescape(str) {
  return str
      .replace(/&amp;/g, '&')
      .replace(/&quot;/g, '"')
      .replace(/&#39;/g, "'")
      .replace(/&lt;/g, '<')
      .replace(/&gt;/g, '>')
      .replace(/&#x2F/g, '/')
      .replace(/&#x3D;/g, '=')
      .replace(/&#x60;/g, '`');
}
oscar castellon
  • 3,048
  • 30
  • 19
-2

This answer provides the jQuery and normal JS methods, but this is shortest without using the DOM:

unescape(escape("It's > 20% less complicated this way."))

Escaped string: It%27s%20%3E%2020%25%20less%20complicated%20this%20way.

If the escaped spaces bother you, try:

unescape(escape("It's > 20% less complicated this way.").replace(/%20/g, " "))

Escaped string: It%27s %3E 20%25 less complicated this way.

Unfortunately, the escape() function was deprecated in JavaScript version 1.5. encodeURI() or encodeURIComponent() are alternatives, but they ignore ', so the last line of code would turn into this:

decodeURI(encodeURI("It's > 20% less complicated this way.").replace(/%20/g, " ").replace("'", '%27'))

All major browsers still support the short code, and given the number of old websites, i doubt that will change soon.

Community
  • 1
  • 1
Cees Timmerman
  • 17,623
  • 11
  • 91
  • 124
  • This is for URL encoding. The question was about HTML escaping, which is very different. – thelem Oct 15 '15 at 09:22
  • @thelem, not if the strings are embedded in JavaScript arrays embedded in HTML, but i agree it was about plain HTML escaping so it can be immediately displayed as text. – Cees Timmerman Oct 15 '15 at 13:02
-2

All solutions are useless if you dont prevent re-escape, e.g. most solutions would keep escaping & to &amp;.

escapeHtml = function (s) {
    return s ? s.replace(
        /[&<>'"]/g,
        function (c, offset, str) {
            if (c === "&") {
                var substr = str.substring(offset, offset + 6);
                if (/&(amp|lt|gt|apos|quot);/.test(substr)) {
                    // already escaped, do not re-escape
                    return c;
                }
            }
            return "&" + {
                "&": "amp",
                "<": "lt",
                ">": "gt",
                "'": "apos",
                '"': "quot"
            }[c] + ";";
        }
    ) : "";
};
Alexander Elgin
  • 6,796
  • 4
  • 40
  • 50
  • 4
    That's called double escaping and should be fixed by making sure your input data is not already escaped. What if you wanted to literally show < to the user? Or perhaps the text is going to be reused elsewhere, and depend on the escaping having happened? – thelem Oct 15 '15 at 09:26
-3

If you are saving this information in a database, its wrong to escape HTML using a client-side script, this should be done in the server. Otherwise its easy to bypass your XSS protection.

To make my point clear, here is a exemple using one of the answers:

Lets say you are using the function escapeHtml to escape the Html from a comment in your blog and then posting it to your server.

var entityMap = {
    "&": "&amp;",
    "<": "&lt;",
    ">": "&gt;",
    '"': '&quot;',
    "'": '&#39;',
    "/": '&#x2F;'
  };

  function escapeHtml(string) {
    return String(string).replace(/[&<>"'\/]/g, function (s) {
      return entityMap[s];
    });
  }

The user could:

  • Edit the POST request parameters and replace the comment with javascript code.
  • Overwrite the escapeHtml function using the browser console.

If the user paste this snippet in the console it would bypass the XSS validation:

function escapeHtml(string){
   return string
}
Kauê Gimenes
  • 1,278
  • 1
  • 13
  • 30
  • I disagree. To bypass this XSS protection you'd have to use a XSS attack (injecting a script that disables the escaping), which is what you are actually blocking. In certain cases it's actually more appropriate to escape on the client, for example if the data comes from a REST API that has to return standard JSON. – ItalyPaleAle Mar 13 '15 at 18:00
  • @Qualcuno If you are doing this validation in the client and posting this information to the server trusting it was validated the user could simply edit the request and the script would be saved in the database. – Kauê Gimenes Mar 13 '15 at 18:12
  • @Qualcuno I included some examples to make my point more clear. – Kauê Gimenes Mar 13 '15 at 18:21
  • 1
    The question was about escaping strings received from the server to **display** them on the browser. What you are saying is about escaping strings before submitting them to the server, which is a different thing (though you're right, there, and it goes back to the old rule *never blindly accept any input from the client*) – ItalyPaleAle Mar 13 '15 at 18:26
  • @Qualcuno This is a popular question in Stackoverflow, and i believe this is an important point to be covered. Thats why i answered. – Kauê Gimenes Mar 13 '15 at 18:29
  • @Qualcuno And the answer is pretty open, thats why i think we should cover all the points. – Kauê Gimenes Mar 13 '15 at 18:31