• 安全地使用v-html


    vue2

    1、 使用插件DOMPurify

    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); } },
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    2、手动写过滤函数

    <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>
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46

    属性对象的类型: NamedNodeMap ,表示属性节点 Attr 对象的集合

    vue3

  • 相关阅读:
    大佬们redis里面的这些数据拿出来怎么转换成正常字符?
    docker 查看容器挂载情况
    好用的博客评论系统 Valine 使用及避坑指南
    基于Delta Lake构建数据湖仓体系
    ubuntu-samba创建
    python-List&tuple&dict
    列表和字典练习
    Rust 笔记:Rust 语言中的字符串
    Mysql表的操作
    Windows 10 开启子系统Ubuntu
  • 原文地址:https://blog.csdn.net/m0_51754096/article/details/136790489