安全地使用v-html

发布于:2024-03-18 ⋅ 阅读:(133) ⋅ 点赞:(0)

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


网站公告

今日签到

点亮在社区的每一天
去签到