安全地使用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

当然,能不用v-html就不用v-html,因为不安全又麻烦,如果是使用富文本编辑器生成的标签,那么直接使用富文本展示数据即可,只需要按照需求去掉toolbar

如:使用富文本编辑器,具体例子看链接

  • 7
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值