DOMPurify是一个开源的基于DOM的快速XSS净化工具。输入HTML元素,然后通过DOM解析递归元素节点,进行净化,输出安全的HTML
<div v-html="sanitizedContent"></div>
import DOMPurify from 'dompurify';
data () {
return {
htmlContent: 'Hello, World!
'
}
},
computed: {
sanitizedContent () {
return DOMPurify.sanitize(this.htmlContent);
}
},
<template>
<div>
<div v-html="sanitizedContent"></div>
</div>
</template>
<script>
export default {
data() {
return {
htmlContent: 'Hello, World!
'
};
},
computed: {
sanitizedContent() {
return this.sanitizeHTML(this.htmlContent);
}
},
methods: {
sanitizeHTML(html) {
//允许的标签
const allowedTags = ['p', 'a'];
//允许的标签属性
const allowedAttributes = ['href'];
const tempDiv = document.createElement('div');
tempDiv.innerHTML = html;
tempDiv.querySelectorAll('*').forEach(element => {
if (!allowedTags.includes(element.tagName.toLowerCase())) {
element.remove();
} else {
Array.from(element.attributes).forEach(attribute => {
if (!allowedAttributes.includes(attribute.name)) {
element.removeAttribute(attribute.name);
}
});
}
});
return tempDiv.innerHTML;
}
}
};
</script>
属性对象的类型: NamedNodeMap ,表示属性节点 Attr 对象的集合