共计 989 个字符,预计需要花费 3 分钟才能阅读完成。
首先能够看一下 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) }
正文完
发表至: javascript
2021-08-20