TrustedTypePolicyFactory: createPolicy() method

Limited availability

This feature is not Baseline because it does not work in some of the most widely-used browsers.

Note: This feature is available in Web Workers.

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

The default policy

In Chrome a policy with a name of "default" creates a special policy that will be used if a string (rather than a Trusted Type object) is passed to an injection sink. This can be used in a transitional phase while moving from an application that inserted strings into injection sinks.

Note: The above behavior is not yet settled in the specification and may change in future.

Warning: A lax default policy could defeat the purpose of using Trusted Types, and therefore should be defined with strict rules to ensure it cannot be used to run dangerous code.


createPolicy(policyName, policyOptions)



A string with the name of the policy.

policyOptions Optional

User-defined functions for converting strings into trusted values.


A callback function in the form of a string that contains code to run when creating a TrustedHTML object.


A callback function in the form of a string that contains code to run when creating a TrustedScript object.


A callback function in the form of a string that contains code to run when creating a TrustedScriptURL object.

Return value



Thrown if policy names are restricted by the Content Security Policy trusted-types directive and this name is not on the allowlist.


Thrown if the name is a duplicate and the Content Security Policy trusted-types directive is not using allow-duplicates.


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, "<"),

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, the following default policy will be used.

The 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(


Trusted Types
# dom-trustedtypepolicyfactory-createpolicy

Browser compatibility

BCD tables only load in the browser