首先可以看一下xss的定义与基础思路
前端安全系列(一):如何防止XSS攻击?
安装
$ npm install xss
配置文件
// @/utils/xss.j const xss = require('xss') const options = { css: false, onTag(tag, html, options) { if (tag === 'iframe') { return html.replace(/javascript:?/, '') } }, // 避免把页面样式过滤掉 onIgnoreTagAttr(tag, name, value, isWhiteAttr) { // 过滤掉标签上的事件 if (/^[^on]/.test(name)) { return name + '="' + xss.escapeAttrValue(value) + '"' } }, } const filter = new xss.FilterXSS(options) export default filter
挂载全局
// @/main.js import xss from '@/utils/xss' // ... Vue.prototype.$xss = xss // 挂在全局是为了在 loader中能够通过该方法去过滤全局的 v-html 返回数据
模块预处理
// vue.config.js // ... module.exports = { // ... chainWebpack: config => { // ... // 增加 xss 处理 config.module .rule('vue') .use('vue-loader') .loader('vue-loader') .tap(options => { options.compilerOptions.directives = { html (node, directiveMeta) { const props = node.props || (node.props = []) props.push({ name: 'innerHTML', value: `$xss.process(_s(${directiveMeta.value}))`, }) }, } return options }) }, }
页面内提交表单等情况时使用
// @/views/demo/index.vue <script> import xss from '@/utils/xss' // ... function onInput(val) { return xss.process(str) }
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。