我们也遇到了同样的问题。
以下是您解决问题的方法:
-
安装DOMPurify 库。 npm install --save DOMPurify
-
创建一个文件trusted-security-policies.js。
-
在您的打包程序的入口点(例如 webpack)中,首先(在可能违反内容安全政策的任何代码之前)导入此文件:
import './path/to/trusted-security-policies';
import DOMPurify from 'dompurify';
if (window.trustedTypes && window.trustedTypes.createPolicy) { // Feature testing
window.trustedTypes.createPolicy('default', {
createHTML: (string) => DOMPurify.sanitize(string, {RETURN_TRUSTED_TYPE: true}),
createScriptURL: string => string, // warning: this is unsafe!
createScript: string => string, // warning: this is unsafe!
});
}
这是做什么的:每当一个字符串被分配以被解析为 HTML,或者作为一个 URL,或者作为一个脚本,浏览器自动 strong> 通过定义的处理函数传递这个字符串。
对于 HTML,DOMPurify 库正在从潜在的 XSS 代码中清除 HTML。
对于scriptURL 和script,字符串只是通过。 请注意,这实际上会禁用这两个部分的安全性,并且只应在您尚未确定如何使这些字符串自己安全的情况下使用。一旦你有了它,相应地替换处理函数。
编辑,2021 年 12 月:我可以contribute to DOMPurify,所以如果您需要使用自定义元素,现在该库也可以configured 工作在您的 HTML 字符串中,以及 自定义属性(release 2.3.4 之前的属性在清理过程中被简单地删除):
/**
* Control behavior relating to Custom Elements
*/
// DOMPurify allows to define rules for Custom Elements. When using the CUSTOM_ELEMENT_HANDLING
// literal, it is possible to define exactly what elements you wish to allow (by default, none are allowed).
//
// The same goes for their attributes. By default, the built-in or configured allow.list is used.
//
// You can use a RegExp literal to specify what is allowed or a predicate, examples for both can be seen below.
// The default values are very restrictive to prevent accidental XSS bypasses. Handle with great care!
var clean = DOMPurify.sanitize(
'<foo-bar baz="foobar" forbidden="true"></foo-bar><div is="foo-baz"></div>',
{
CUSTOM_ELEMENT_HANDLING: {
tagNameCheck: null, // no custom elements are allowed
attributeNameCheck: null, // default / standard attribute allow-list is used
allowCustomizedBuiltInElements: false, // no customized built-ins allowed
},
}
); // <div is=""></div>
var clean = DOMPurify.sanitize(
'<foo-bar baz="foobar" forbidden="true"></foo-bar><div is="foo-baz"></div>',
{
CUSTOM_ELEMENT_HANDLING: {
tagNameCheck: /^foo-/, // allow all tags starting with "foo-"
attributeNameCheck: /baz/, // allow all attributes containing "baz"
allowCustomizedBuiltInElements: false, // customized built-ins are allowed
},
}
); // <foo-bar baz="foobar"></foo-bar><div is=""></div>
var clean = DOMPurify.sanitize(
'<foo-bar baz="foobar" forbidden="true"></foo-bar><div is="foo-baz"></div>',
{
CUSTOM_ELEMENT_HANDLING: {
tagNameCheck: (tagName) => tagName.match(/^foo-/), // allow all tags starting with "foo-"
attributeNameCheck: (attr) => attr.match(/baz/), // allow all containing "baz"
allowCustomizedBuiltInElements: true, // allow customized built-ins
},
}
); // <foo-bar baz="foobar"></foo-bar><div is="foo-baz"></div>