我正在使用以下方法绑定html并显示在我的页面中。它工作完美,但是我收到来自 eslint 的警告,“v-html”指令可能导致 XSS 攻击。eslint(vue/no-v-html)
<button
id="foreignerBtn"
class="tabButton"
@click="foreignerClick"
v-html="textContent2"
></button>
然后我按照以下方法更改它。但我无法渲染 html 标签。
<button
id="foreignerBtn"
class="tabButton"
@click="foreignerClick"
>{{ textContent2 }}</button>
正如 Decade Moon 提到的,如果传递给 v-html 的内容是经过净化的 HTML,则可以禁用该规则。
https://eslint.vuejs.org/rules/no-v-html.html
通过将 html 包裹起来来禁用规则
<!-- eslint-disable vue/no-v-html -->
<button
id="foreignerBtn"
class="tabButton"
@click="foreignerClick"
v-html="textContent2"
></button>
<!--eslint-enable-->
如其他答案中所述,您可以禁用警告,但一个好的做法是确保正确禁用该规则。
为此,您可以使用 dompurify 来解析您提供给浏览器的 HTML,删除任何恶意部分并安全地显示它。
问题仍然存在,但你可以使用 RisXSS,这是一个 ESLint 插件,它会警告使用
v-html
if 你之前没有清理它(从某种意义上说,这是 vue/no-v-html
的改进版本) ESLint 规则)。
为此,请安装
dompurify
和 eslint-plugin-risxss
:
npm install dompurify eslint-plugin-risxss
将
risxss
添加到您的 ESLint 插件,然后使用 DOMPurify:
<template>
<button
id="foreignerBtn"
class="tabButton"
@click="foreignerClick"
v-html="sanitizedTextContent2"
<!-- no warning, good to go -->
></button>
<button
id="foreignerBtn"
class="tabButton"
@click="foreignerClick"
v-html="textContent2"
<!-- warning here -->
></button>
</template>
<script>
import DOMPurify from 'dompurify';
export default {
data () {
return {
sanitizedTextContent2: DOMPurify.sanitize(textContent2)
}
}
}
</script>
免责声明:我是 RisXSS 插件的贡献者。
您可以将代码包装在
<!-- eslint-disable -->
<button
id="foreignerBtn"
class="tabButton"
@click="foreignerClick"
v-html="textContent2"
></button>
<!-- eslint-enable -->
它将隐藏所有 eslint 警告,包括 v-html
我想禁用我的整个项目,所以我在“eslintConfig”的“规则”中添加了这一行
"eslintConfig": {
...
"rules": {
...
"vue/no-v-html": "disable"
}