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

TrustedTypePolicyFactory: createPolicy() method

· 52CE 我爱测

The **`createPolicy()`** method of the TrustedTypePolicyFactory interface creates a TrustedTypePolicy object that implements the rules passed as `policyOptions`.

Trusted Types API

The createPolicy() method of the TrustedTypePolicyFactory interface creates a TrustedTypePolicy object that implements the rules passed as policyOptions.

Syntax

createPolicy(policyName, policyOptions)

Parameters

  • policyName
    • : A string with the name of the policy.
  • policyOptions
    • : User-defined functions for converting strings into trusted values.
      • createHTML(input[,args])
        • : A callback function in the form of a string that contains code to run when creating a TrustedHTML object.
      • createScript(input[,args])
        • : A callback function in the form of a string that contains code to run when creating a TrustedScript object.
      • createScriptURL(input[,args])
        • : A callback function in the form of a string that contains code to run when creating a TrustedScriptURL object.

Return value

A TrustedTypePolicy object.

Exceptions

Examples

Creating a policy for HTML sinks

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

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

Creating a default policy

On a site where Trusted Types are enforced via a Content Security Policy with the require-trusted-types-for directive set to script, any injection script that accepts a script expects a Trusted Type object. In the case that a string is inserted instead, a default policy will be used.

The default policy logs a message to the console to remind the developer to refactor this part of the application to use a Trusted Type object. It also appends details of the use of the default policy, type, and injection sink to the returned value.

trustedTypes.createPolicy("default", {
  createScriptURL(s, type, sink) {
    console.log("Please refactor.");
    return `${s}?default-policy-used&type=${encodeURIComponent(
      type,
    )}&sink=${encodeURIComponent(sink)}`;
  },
});

Specifications

Browser compatibility

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

资料来源与适用范围

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

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

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