大网数据广告活动
Web 标准与前端开发

TrustedTypePolicyFactory

· 52CE 我爱测

The **`TrustedTypePolicyFactory`** interface of the Trusted Types API creates policies and allows the verification of Trusted Type objects against created policies.

Trusted Types API

The TrustedTypePolicyFactory interface of the Trusted Types API creates policies and allows the verification of Trusted Type objects against created policies.

Instance properties

  • TrustedTypePolicyFactory.emptyHTML
    • : Returns a TrustedHTML object containing an empty string.
  • TrustedTypePolicyFactory.emptyScript
    • : Returns a TrustedScript object containing an empty string.
  • TrustedTypePolicyFactory.defaultPolicy
    • : Returns the default TrustedTypePolicy or null if this is empty.

Instance methods

  • TrustedTypePolicyFactory.createPolicy()
    • : Creates a TrustedTypePolicy object that implements the rules passed as policyOptions.
  • TrustedTypePolicyFactory.isHTML()
    • : When passed a value checks that it is a valid TrustedHTML object.
  • TrustedTypePolicyFactory.isScript()
    • : When passed a value checks that it is a valid TrustedScript object.
  • TrustedTypePolicyFactory.isScriptURL()
    • : When passed a value checks that it is a valid TrustedScriptURL object.
  • TrustedTypePolicyFactory.getAttributeType()
    • : Allows web developers to check whether a Trusted Type is required for an element and attribute, and if so which one.
  • TrustedTypePolicyFactory.getPropertyType()
    • : Allows web developers to check whether a Trusted Type is required for a property, and if so which one.

Examples

The below code creates a policy with the name "myEscapePolicy" with a function defined for createHTML() which sanitizes HTML.

We then use the policy to sanitize a string, creating a TrustedHTML object, escaped. This object can be tested with TrustedTypePolicyFactory.isHTML to ensure that it was created by one of our policies.

const escapeHTMLPolicy = trustedTypes.createPolicy("myEscapePolicy", {
  createHTML: (string) => string.replace(/</g, "&lt;"),
});

const escaped = escapeHTMLPolicy.createHTML("<img src=x onerror=alert(1)>");

console.log(trustedTypes.isHTML(escaped)); // true;

Specifications

Browser compatibility

来源:MDN Web Docs / Mozilla 贡献者 · 作者与贡献记录 · CC BY-SA 2.5。离线整理了版式、链接和媒体显示。

资料来源与适用范围

资料来源
MDN Web Docs / Mozilla 贡献者
适用范围
请按文中版本与环境说明核对
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 2.5

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。