vue2
1、 使用插件DOMPurify
DOMPurify是一个开源的基于DOM的快速XSS净化工具。输入HTML元素,然后通过DOM解析递归元素节点,进行净化,输出安全的HTML
<div v-html="sanitizedContent"></div>import DOMPurify from 'dompurify'; data () {return {htmlContent: '<p>Hello, <a href="https://example.com">World</a>!</p>'}},computed: {sanitizedContent () {return DOMPurify.sanitize(this.htmlContent);}},
2、手动写过滤函数
<template><div><div v-html="sanitizedContent"></div></div>
</template><script>
export default {data() {return {htmlContent: '<p>Hello, <a href="https://example.com" target="_blank">World</a>!</p>'};},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 对象的集合
vue3
- vue3多了一个方法
http://www.mobiletrain.org/about/BBS/256788.html
利用createVNode方法,用递归的方式,创建虚拟DOM,在构建虚拟DOM树之前,可以对输入的HTML内容进行过滤和处理。