简体   繁体   English

将数据加载到div时如何防止XSS?

[英]How to prevent XSS when loading data into div?

I'm fetching data with Ajax (JSON) parsing that then into a template like this: 我正在使用Ajax(JSON)解析获取数据然后进入这样的模板:

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. 然后使用jQuery将其附加到div。 Now if obj.name or obj.content contains any JS, those will be executed. 现在,如果obj.nameobj.content包含任何JS,那么将执行这些。

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: 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. .text()为你清理它。

Thanks to @Rory McCrossan for the idea! 感谢@Rory McCrossan的想法!

The issue would be how you append the HTML the function returns to the DOM, not how you generate the HTML itself. 问题是你如何追加函数返回给DOM的HTML,而不是如何生成HTML本身。

If you append the content of the element using jQuery's text() method it will be sanitised for you, something like this: 如果使用jQuery的text()方法追加元素的内容,它将为您清理,如下所示:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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