首先,我以html的形式从API返回。这将在我的jqgrid中使用。示例返回与我的对象的示例名称类似,它是obj。那么obj.something就在下面。
<div title="custom_title">
<div id="upper">
data from somewhere and this is the part that sometimes need to be sanitized without affecting the other tags
</div>
</div>到目前为止,我尝试的是尝试这样做: var esc = $('');然后做了以下操作:esc.text(obj.something).html();,但是它对所有这些都进行了消毒。有什么是我可能不知道如何纯粹在javascript上消毒吗?
任何帮助都是非常感谢的。
发布于 2016-06-02 20:06:50
在这种情况下,您可以使用DOMPurify
DOMPurify清除HTML并防止XSS攻击。您可以向DOMPurify提供充满脏HTML的字符串,它将返回一个带有干净HTML的字符串。DOMPurify将删除所有包含危险HTML的内容,从而防止XSS攻击和其他恶意行为。
发布于 2015-03-08 11:55:59
这里同意@Juhana:“返回包装在HTML中的未经消毒的输出确实是您应该避免的事情。”但是,如果没有,并且希望控制和净化DOM,可以在普通的JS中这样做:
obj = {};
obj.something = '<div title="custom_title"><div id="upper">data from somewhere and this is the part that sometimes need to be sanitized without affecting the other tags</div></div>';
var container = document.createElement("div"); //create an element in memory
container.insertAdjacentHTML('afterbegin', obj.something); //serialize the HTML string into the structure.
container.querySelector("#upper").innerHTML = ""; //empty the element, removing the data in it. (or do something else with it, like stripping all the a elements that do not start with http(s).
console.log(container)<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
它将HTML呈现为内存中的元素,使您无法对其执行DOM操作,并使用id upper删除div的内容。完成后,将容器div的内容插入到网格中。
https://stackoverflow.com/questions/28925925
复制相似问题