Javascript sanitization: the safest way to insert a possible XSS html string

I am currently using this method with a jQuery solution to clear a line of possible XSS attacks.

sanitize:function(str) {
    // return htmlentities(str,'ENT_QUOTES');
    return $('<div></div>').text(str).html().replace(/"/gi,'&quot;').replace(/'/gi,'&apos;');   
}

But I have a feeling that it’s not safe enough. Did I miss something?

I tried htmlentities from phpjs project here: http://phpjs.org/functions/htmlentities:425/

But it seems to be listening and returns some additional special characters. Maybe this is an old version?

For instance:

htmlentities('test"','ENT_QUOTES');

It produces:

test&amp;quot;

But it should be:

test&quot;

How do you handle this through javascript?

+5
source share
3 answers

HTML, .createTextNode(text)/ .data node. , , .

+3

javascript. .

. jQuery

var str = '<div>abc"def"ghi</div>​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​';

​$​('test').text(str);
$('test').attr('alt', str);

.

: http://jsfiddle.net/HNQvd/

+3

: ' " < > ( ) ; XSS attacsk.

+1

All Articles