首先能够看一下xss的定义与根底思路

前端平安系列(一):如何避免XSS攻打?
  1. 装置

    $ npm install xss
  2. 配置文件

    // @/utils/xss.jconst 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
  3. 挂载全局

    // @/main.jsimport xss from '@/utils/xss'// ...Vue.prototype.$xss = xss // 挂在全局是为了在 loader中可能通过该办法去过滤全局的 v-html 返回数据
  4. 模块预处理

    // 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   })  },}
  5. 页面内提交表单等状况时应用

    // @/views/demo/index.vue<script>import xss from '@/utils/xss'// ...function onInput(val) {  return xss.process(str)}