TrustedTypePolicyFactory: createPolicy() method
{{APIRef("Trusted Types API")}} {{AvailableInWorkers}}
The createPolicy() method of the {{domxref("TrustedTypePolicyFactory")}} interface creates a {{domxref("TrustedTypePolicy")}} object that implements the rules passed as policyOptions.
Syntax
createPolicy(policyName, policyOptions)
Parameters
policyName- : A string with the name of the policy.
policyOptions{{optional_inline}}- : 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
{{domxref("TrustedHTML")}}object.
- : A callback function in the form of a string that contains code to run when creating a
createScript(input[,args])- : A callback function in the form of a string that contains code to run when creating a
{{domxref("TrustedScript")}}object.
- : A callback function in the form of a string that contains code to run when creating a
createScriptURL(input[,args])- : A callback function in the form of a string that contains code to run when creating a
{{domxref("TrustedScriptURL")}}object.
- : A callback function in the form of a string that contains code to run when creating a
- : User-defined functions for converting strings into trusted values.
Return value
A {{domxref("TrustedTypePolicy")}} object.
Exceptions
{{jsxref("TypeError")}}- : Thrown if policy names are restricted by the Content Security Policy
trusted-typesdirective and this name is not on the allowlist.
- : Thrown if policy names are restricted by the Content Security Policy
{{jsxref("TypeError")}}- : Thrown if the name is a duplicate and the Content Security Policy trusted-types directive is not using
allow-duplicates.
- : Thrown if the name is a duplicate and the Content Security Policy trusted-types directive is not using
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, "<"),
});
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
{{Specifications}}
Browser compatibility
{{Compat}}