简体   繁体   中英

How can I prevent XSS for an keyup() jQuery event?

I am making a form with an keyup() event: every character the user types is immediately displayed into another div on the same page.

It's vulnerable to XSS. How can I secure it using jQuery?

Note: In my forms, I am using latin alphanumeric characters only, as well as commas, semi-colons, colons.

I have searched the "Reform" tool from OWASP but is there a way that's better?

Thanks in advance. Regards

With the few details available: remember that you don't have to use jQuery's HTML "parsing" for everything. Instead of using .html() , use DOM manipulations and .text() (which are also usually faster). For example, this:

$('#result').html('<span class="whatever">' + someInput + '</span>');

would become this:

$('#result').text($('<span>').addClass('whatever').text(someInput));

If that's not possible, you can also do flawless HTML escaping by setting with .text() and then fetching it with .html() . For example, this:

var data = 'This text: **is bold**';

$('#result').html(data.replace(/\*\*(.+?)\*\*/g, '<b>$1</b>'));

would become this:

var data = 'This text: **is bold**';

$('#result').html(data.replace(/\*\*(.+?)\*\*/g, function(x) {
    return '<b>' + $('<div>').text(x).html() + '</b>';
}));

I've found the xss cleaner included in node-validator to be comprehensive. The code you're interested in is available here . You'll need to clean it up a little to use in the browser (remove the module.exports and wrap in a Javascript closure instead) but it should work pretty seamlessly. If you wanted to, you could make it directly into a JQuery plug-in as well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM