当前位置: 首页 > news >正文

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

  • vue3多了一个方法
    http://www.mobiletrain.org/about/BBS/256788.html
    利用createVNode方法,用递归的方式,创建虚拟DOM,在构建虚拟DOM树之前,可以对输入的HTML内容进行过滤和处理。
http://www.lryc.cn/news/319803.html

相关文章:

  • MongoDB从0到1:高效数据使用方法
  • Go——运算符,变量和常量,基本类型
  • js使用canvas实现图片鼠标滚轮放大缩小拖拽预览,显示像素坐标,显示像素值
  • ArrayList 源码解析和设计思路
  • Win10系统使用IIS服务搭建WebDAV网站结合内网穿透公网访问本地文件
  • AWTK 开源串口屏的配置文件
  • Spring、SpringMVC、Spring Boot常见注解有哪些?不要混淆了哦
  • 在notion里面实现四象限清单
  • 【linux】搜索所有目录和子目录下的包含.git的文件并删除
  • 三、传输层拥塞控制、差错控制
  • 主流电商平台数据大规模数据采集接口的实现:电商API接口接入方案和电商数据采集现状
  • Python电梯楼层数字识别
  • Linux学习:基础开发工具的使用(1)
  • 在idea中配置tomcat服务器,然后部署一个项日
  • C语言例:设 int a=11; 则表达式 a+=a-=a*a 的值
  • C++ 中的虚函数和多态性
  • 叶顺舟:手机SoC音频趋势洞察与端侧AI技术探讨 | 演讲嘉宾公布
  • SpringBoot之yml与properties配置文件格式的区别
  • 【递归搜索回溯专栏】专题二:二叉树中的深搜----二叉树剪枝
  • Django实现登录注册
  • Python实战:NumPy数组与矩阵操作入门
  • 2024.2.26校招 实习 内推 面经
  • cannot find -xml2: No such file or directory的解决方法
  • linux下的进程间通信
  • 基于单片机的IC 卡门禁系统设计
  • 【爬虫介绍】了解爬虫的魅力
  • Xcode 15.3 Archive失败
  • Hadoop学习3:问题解决
  • HarmonyOS鸿蒙开发常用4种布局详细说明
  • Python中的变量是什么类型?