解决Vue-markdown编辑器加入xss之后,code标签里的代码块会被转义的问题

mavonEditor

一、简单的介绍一下关于vue-markdown的使用

  • 安装
 npm install mavon-editor --save
  • 引入(在main.js中全局引入)
import Vue from 'vue'
import mavonEditor from 'mavon-editor'
import 'mavon-editor/dist/css/index.css';
Vue.use(mavonEditor);
  • 使用
 <mavon-editor  v-model="value" ></mavon-editor>

二、问题:考虑到了安全性问题使用了js-xss做过滤,导致code标签里的标签会被解析

  1. 预期效果:code标签的代码块不能被解析,用户输入的内容与展示的内容一一对应,前提条件也需要考虑到安全性问题
  2. 解决思路:
    1.渲染时用mavon-editor 底层 markdown-it 的 api 将字符串转换为 html 片段
    2.用拿到的 html 片段用 js-xss 做过滤,然后用 v-html 渲染
    3.具体实现的代码如下:
    加入xss过滤(main.js)
    import filterXSS from 'xss'
    filterXSS.whiteList['input'] = ['type', 'src', 'disabled', 'checked', 'class']
    filterXSS.whiteList['img'] = ['src', 'alt', 'title', 'width', 'max-width', 'style', 'height']
    filterXSS.whiteList['math'] = []
    filterXSS.whiteList['semantics'] = []
    filterXSS.whiteList['mrow'] = []
    filterXSS.whiteList['mtext'] = []
    filterXSS.whiteList['annotation'] = ['encoding']
    filterXSS.whiteList['msub'] = []
    filterXSS.whiteList['mi'] = []
    filterXSS.whiteList['mo'] = []
    filterXSS.whiteList['mn'] = []
    filterXSS.whiteList['li'] = ['class']
    filterXSS.whiteList['span'] = ['class', 'title', 'aria-hidden', 'style']
    filterXSS.whiteList['code'] = []
    filterXSS.whiteList['li'] = ['class', 'id']
    filterXSS.whiteList['td'] = ['style', 'class']
    filterXSS.whiteList['p'] = ['style', 'class']
    filterXSS.whiteList['div'] = ['style', 'class']
    filterXSS.whiteList['a'] = ['style', 'class', 'id', 'target', 'href', 'title']
    filterXSS.stripIgnoreTag = true
    Vue.prototype.filterXSS = filterXSS;
    
    展示的内容
    <template>
        <div class="preview-wrapper" v-html="showData"></div>
    </template>
    <script>
        import mavonEditor from 'mavon-editor';
        export default {
            props: {
                previewInfo: {
                    type: String,
                    default: ''
                }
            },
            data () {
                return {
                    showData: ''
                }
            },
            mounted () {
                this.initMrakdownContent()
            },
            methods: {
                initMrakdownContent () {
                    const data = mavonEditor.markdownIt.render(this.previewInfo)
                    this.showData = filterXSS(data)
                }
            }
        }
    </script>
    
    previewInfo为用户编辑的内容

你可能感兴趣的:(vue)