简体   繁体   中英

How to prevent XSS when loading data into div?

I'm fetching data with Ajax (JSON) parsing that then into a template like this:

function noteTemplate(obj) {
    var date = obj.created_at.split(/[- :]/),
        dateTime = date[2] + '.' + date[1] + '.' + date[0];
        dateTime += ' @ ' + date[3] + ':' + date[4] + ':' + date[5];

    var note = '<div class="note-container" target="' + obj.id + '">';
        note += '<div class="note-options"><div class="note-remove"></div></div>';
        note += '<div class="note-name">' + obj.name + '</div>';
        note += '<div class="note-date">' + dateTime + '</div>';
        note += '<div class="note-content">' + obj.content + '</div>';
        note += '</div>';
    return note;
}

And then appending that to a div using jQuery. Now if obj.name or obj.content contains any JS, those will be executed.

What would be the most proper way to prevent that? Thanks

Update:

I found a solution and in native way by escaping < > and replacing them with entities like this does the job.

obj.content.replace(/</g, "&lt;").replace(/>/g, "&gt;")

jQuery:

var $note = $(note);
$note.find('.note-name').text(obj.name);
$note.find('.note-content').text(obj.content);

return $note;

.text() sanitazes it for you.

Thanks to @Rory McCrossan for the idea!

The issue would be how you append the HTML the function returns to the DOM, not how you generate the HTML itself.

If you append the content of the element using jQuery's text() method it will be sanitised for you, something like this:

$('#myElement').text(noteTemplate(data));

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