使用 `setHTML()` 实现完美类型
Sat 07 March 2026
Sat 07 March 2026
TLDR: Use require-trusted-types-for 'script'; trusted-types 'none'; in your CSP and nothing besides setHTML() works, essentially removing all DOM-XSS risks.
TLDR: 在你的 CSP 中使用 require-trusted-types-for 'script'; trusted-types 'none';,除了 setHTML() 之外什么都不工作,基本上消除了所有 DOM-XSS 风险。
Background: Sanitizer API
背景:Sanitizer API
I was guest at the ShopTalkShow Podcast to talk about setHTML() and the HTML Sanitizer API. Feel free to listen to the whole episode, if you want to take it all in. It's a great introduction.
我曾是 ShopTalkShow Podcast 的嘉宾,谈论 setHTML() 和 HTML Sanitizer API。如果你想全面了解,请随意收听整个剧集。这是一个很好的介绍。
Meanwhile, MDN has a good explanation of the Sanitizer constructor to create a custom configuration and Element.setHTML() as the main entry point of the API. People who do not want to directly insert into the document can also create a new document with Document.parseHTML().
同时,MDN 对 Sanitizer 构造函数有一个很好的解释,用于创建自定义配置,以及 Element.setHTML() 作为 API 的主要入口点。不想直接插入文档的人也可以使用 Document.parseHTML() 创建一个新文档。
Trusted Types
Trusted Types
Trusted Types (TT) is a feature in Content-Security-Policy (CSP), that can help prevent DOM-based XSS. By enabling "trusted types" in your CSP, with a policy like so require-trusted-types-for 'script'; trusted-types 'mypolicy', scripts will not be able to start HTML parsing/insertion from normal strings (e.g., through document.write(), innerHTML= and so on). These so-called HTML parsing sinks will now only accept TrustedHTML objects - hence the name trusted. Creating these types is ideally controlled with a so-called TrustedTypePolicy that is also allowed per the header (mypolicy in the example above).
Trusted Types (TT) 是Content-Security-Policy (CSP) 中的一项功能,可以帮助防止 DOM-based XSS。通过在您的 CSP 中启用 "trusted types",使用如下策略require-trusted-types-for 'script'; trusted-types 'mypolicy',脚本将无法从普通字符串开始 HTML 解析/插入(例如,通过document.write()、innerHTML= 等)。这些所谓的HTML parsing sinks现在只接受TrustedHTML对象——因此得名 trusted。创建这些类型理想情况下由所谓的TrustedTypePolicy来控制,该策略也在头部中被允许(上述示例中的mypolicy)。
I would argue that...