-
Notifications
You must be signed in to change notification settings - Fork 22.5k
/
index.md
55 lines (38 loc) · 1.99 KB
/
index.md
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
---
title: TrustedTypePolicy
slug: Web/API/TrustedTypePolicy
page-type: web-api-interface
browser-compat: api.TrustedTypePolicy
---
{{APIRef("Trusted Types API")}}{{AvailableInWorkers}}
The **`TrustedTypePolicy`** interface of the {{domxref("Trusted Types API", "", "", "nocode")}} defines a group of functions which create `TrustedType` objects.
A `TrustedTypePolicy` object is created by {{domxref("TrustedTypePolicyFactory.createPolicy","TrustedTypePolicyFactory.createPolicy()")}} to define a policy for enforcing security rules on input. Therefore, `TrustedTypePolicy` has no constructor.
## Instance properties
- {{domxref("TrustedTypePolicy.name")}} {{ReadOnlyInline}}
- : A string containing the name of the policy.
## Instance methods
- {{domxref("TrustedTypePolicy.createHTML","TrustedTypePolicy.createHTML()")}}
- : Creates a {{domxref("TrustedHTML")}} object.
- {{domxref("TrustedTypePolicy.createScript","TrustedTypePolicy.createScript()")}}
- : Creates a {{domxref("TrustedScript")}} object.
- {{domxref("TrustedTypePolicy.createScriptURL","TrustedTypePolicy.createScriptURL()")}}
- : Creates a {{domxref("TrustedScriptURL")}} object.
## Examples
In the below example we create a policy that will create {{domxref("TrustedHTML")}} objects using {{domxref("TrustedTypePolicyFactory.createPolicy()")}}. We can then use {{domxref("TrustedTypePolicy.createHTML")}} to create a sanitized HTML string to be inserted into the document.
The sanitized value can then be used with {{domxref("Element.innerHTML")}} to ensure that no new HTML elements can be injected.
```html
<div id="myDiv"></div>
```
```js
const escapeHTMLPolicy = trustedTypes.createPolicy("myEscapePolicy", {
createHTML: (string) => string.replace(/</g, "<"),
});
let el = document.getElementById("myDiv");
const escaped = escapeHTMLPolicy.createHTML("<img src=x onerror=alert(1)>");
console.log(escaped instanceof TrustedHTML); // true
el.innerHTML = escaped;
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}