本文介绍了Javascript清理:插入可能的XSS html字符串的最安全方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当前,我将此方法与jQuery解决方案配合使用,以清除可能的XSS攻击中的字符串.

Currently i'm using this method with jQuery solution, to clean string from 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 it's not safe enough. Do i miss something?

我在这里尝试了来自phpjs项目的htmlentities: http://phpjs.org/functions/htmlentities:425/

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

但是它有点bug,并返回了一些其他特殊符号.也许是旧版本?

But it's kinda bugged and returns some additional special symbols. Maybe it's an old version?

例如:

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

产生:

test&amp;quot;

但应该是:

test&quot;

您如何通过javascript处理此问题?

How are you handling this via javascript?

推荐答案

然后,您无需手动对其进行消毒.使用jQuery,您可以编写

Then you don't need to sanitize it manually. With jQuery you can just write

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

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

浏览器将为您从代码中分离数据.

Browser will separate the data from the code for you.

示例: http://jsfiddle.net/HNQvd/

这篇关于Javascript清理:插入可能的XSS html字符串的最安全方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 22:19