介绍
sanitize-html 是用于富文本防止xss攻击的一种安全过滤手段,能够有效过滤 script 标签,以及其他策略性需要忽略的内容。
使用场景
在基于Quill,或者draft.js 开发富文本工具时会用到,或者针对 innerHTML做赋值时会用到
使用方法
npm install sanitize-html --save
import santizeHTML from sanitize-html;
const allowTags = [ 'b', 'i', 'em', 'strong', 'a' ];
const rule = {
allowTags,
allowAttributes: {
'a': [ 'href' ],
'img': ['src']
...
},
allowStyles: {
'font-size': [/^\d+(?:px|em|%)$/]
...
}
}
const cleanHTML = sanitizeHtml(dirtyContent, rule);
div.innerHTMl = cleanHTML