安全地使用v-html

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

相关推荐

  1. 安全使用v-html

    2024-03-18 04:40:03       24 阅读
  2. 【Flask】使用 werkzeug 安全处理密码

    2024-03-18 04:40:03       31 阅读
  3. Vue3-在HTML标签、组件标签上使用v-model

    2024-03-18 04:40:03       29 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-03-18 04:40:03       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-03-18 04:40:03       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-03-18 04:40:03       18 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-03-18 04:40:03       20 阅读

热门阅读

  1. C++内联函数

    2024-03-18 04:40:03       18 阅读
  2. 客户端渲染与服务端渲染

    2024-03-18 04:40:03       22 阅读
  3. 深入了解Android垃圾回收机制

    2024-03-18 04:40:03       27 阅读