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.
createPolicy(policyName, policyOptions)
policyNameA string with the name of the policy.
policyOptions OptionalUser-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.
A TrustedTypePolicy object.
TypeErrorThrown if policy names are restricted by the Content Security Policy trusted-types directive and this name is not on the allowlist.
TypeErrorThrown 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, "<"),
});
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)}`;
},
});
| Desktop | Mobile | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| Chrome | Edge | Firefox | Opera | Safari | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | WebView Android | WebView on iOS | |
createPolicy |
83 | 83 | No | 69 | 26 | 83 | No | 59 | 26 | 13.0 | 83 | 26 |
© 2005–2025 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/API/TrustedTypePolicyFactory/createPolicy