npm库xss依赖的使用方法和vue3 中Web富文本编辑器 wangeditor 使用xss库解决 XSS 攻击的方法
 
  
 
 
1. npm库xss依赖的使用方法
 
1.1 xss库定义
 
- npm中有一个依赖名为xss,是一个可以对用户输入的内容进行过滤以避免遭受 XSS 攻击的js模块。
1.2 xss库功能
 
- 不定义白名单,也不自定义处理函数时,采用xss库默认的过滤规则。
- 可配置标签及标签属性白名单,作为允许的HTML标签及标签属性;
- 可自定义处理函数,针对任意标签及标签属性进行自定义处理。
2. vue3 中 wangeditor 使用xss库解决 XSS 攻击的方法和示例
 
2.1 在终端执行如下命令安装 xss 依赖
 
npm install xss -S
 
2.2 在使用 wangeditor 的地方引入 xss 依赖
 
import xss from 'xss'
 
2.3 xss 依赖使用示例
 
<template>
	<div>
		<div ref="myEditor" style="width: 100%">
		</div>
	</div>
</template>
<script lang="ts" setup>
import xss from 'xss'
import wangeditor from 'wangeditor'
let mailData = reactive({
	id: ''
})
const myEditor = ref(null)
let editorInstance = null
onMounted(() => {
	createWangeditor()
})
const createWangeditor = () => {
	editorInstance = new wangeditor(myEditor.value)
	let config = editorInstance.customConfig ?  editorInstance.customConfig :  editorInstance.config
	config.menus = [
		'head', 
		'bold', 
		'fontName', 
		'fontSize', 
		'underline', 
		'strikeThrough', 
		'indent', 
		'lineHeight', 
		'foreColor', 
		'backColor', 
		'list', 
		'justify' 
	]
	config.fontNames = [
		'黑体',
		'仿宋',
		'楷体',
		'标楷体',
		'华文仿宋',
		'华文楷体',
		'宋体',
		'微软雅黑'
	]
	editorInstance.create()
}
onBeforeUnmount(() => {
	editorInstance = null
})
const handleChange = () => {
	mailData.id = ''
	editorInstance.txt.html('')
	queryDefaultContent().then(res => {
		const {code, data} = res
		if(code === '000') {
			let {id, content} = data
			mailData.id = id
			
			let safeContent = xss(content) 
			editorInstance.txt.html(safeContent)
		}
	})
}
</script>