DOMPurify – 针对 HTML、MathML 和 SVG 的仅支持DOM、快速、高容错的 XSS 过滤器
实例:提交表单,设置XSS过滤
原代码:
<body>
<div class="container">
<form class="add-comment">
<textarea class="comment-text"></textarea>
<br>
<button class="btn btn-primary" value="submit">Post Comment</button>
</form>
<div class="comment"></div>
</div>
<script>
const addCommentForm = document.querySelector('.add-comment');
const textarea = document.querySelector('.comment-text');
const commentDiv = document.querySelector('.comment');
const user = '';
addCommentForm.addEventListener('submit', function (event) {
event.preventDefault(); //取消事件的默认动作
const newConmment = textarea.value.trim();
if (newConmment) {
commentDiv.innerHTML =
`
<div class=" comment-header">${user}</div>
<div class="comment-body">${textarea.value}</div>
`
textarea.value = ``;
}
})
</script>
</body>
引入purify.js
后代码
<body>
<div class="container">
<form class="add-comment">
<textarea class="comment-text"></textarea>
<br>
<button class="btn btn-primary" value="submit">Post Comment</button>
</form>
<div class="comment"></div>
</div>
<script src="https://cdn.bootcss.com/dompurify/1.0.3/purify.js"></script>
<script>
function sanitize(strings, ...values) {
const dirty = strings.reduce((prev, curr, i) => `${prev}${curr}${values[i] || ''}`, '');
return DOMPurify.sanitize(dirty);
}
const addCommentForm = document.querySelector('.add-comment');
const textarea = document.querySelector('.comment-text');
const commentDiv = document.querySelector('.comment');
const user = '';
addCommentForm.addEventListener('submit', function (event) {
event.preventDefault(); //取消事件的默认动作
const newConmment = textarea.value.trim();
if (newConmment) {
commentDiv.innerHTML = sanitize`
<div class=" comment-header">${user}</div>
<div class="comment-body">${textarea.value}</div>
`
textarea.value = ``;
}
})
</script>
</body>
网友评论