如何使用vue-domPurify-html嵌入YouTube视频或任何iframe

2022-06-26 vue.js nuxt.js

我已在Nuxt中创建了一个博客项目,并且正在为我的数据库中的description字段使用quill text editor。

从数据库呈现博客的description时,我使用了v-html,但我收到

34:23警告‘v-html’指令可能导致XSS攻击vue/no-v-html

<span v-html="blog.description"></span>

若要删除此警告,我使用了vue-dompurify-html。

<span v-dompurify-html="blog.description"></span>

现在,当我通过我的quill编辑器添加一个嵌入的视频链接时,domPurify会在呈现时删除视频。对如何将其列入白名单有什么建议吗?


解决方案

这将允许您使用vue-dompurify-html

实现嵌入式Youtube视频
<template>
  <div>
    <div v-dompurify-html="test"></div>
  </div>
</template>

<script>
import Vue from 'vue'
import VueDOMPurifyHTML from 'vue-dompurify-html'

Vue.use(VueDOMPurifyHTML, {
  default: {
    ADD_TAGS: ['iframe'], // this one whitelists Youtube
  },
})

/* eslint-disable no-useless-escape */
/* eslint-disable prettier/prettier */

export default {
  data() {
    return {
      test: '<iframe class="ql-video" frameborder="0" allowfullscreen="true" src="https://www.youtube.com/embed/9_MzJ9QkiHU"></iframe><p><br></p><p><br></p><p>Description</p>'
    }
  }
}
</script>


如果您想从

'<iframe class="ql-video" frameborder="0" allowfullscreen="true" src="https://www.youtube.com/embed/9_MzJ9QkiHU"></iframe><p><br></p><p><br></p><p>Description</p>'

变成更干净的(对于Vue)这样的

"<iframe class='ql-video' frameborder='0' allowfullscreen='true' src='https://www.youtube.com/embed/9_MzJ9QkiHU'></iframe><p><br></p><p><br></p><p>Description</p>"

您可以使用此方法

string.replaceAll('"', "'")

从这个提交中找到了答案:https://github.com/eternagame/eternagame.org/commit/dfcfb6bf8fc77495bb17ea9231091ca5d4f2cbad#diff-841254fe75488c1bd4cd7f68f00b4be0e48dcfbc4a16b45847b68295e0e3b27bL13-R25

相关文章