TrustedHTML
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 inWeb Workers.
TheTrustedHTML interface of theTrusted Types API represents a string that a developer can insert into aninjection sink that will render it as HTML. These objects are created viaTrustedTypePolicy.createHTML() and therefore have no constructor.
The value of aTrustedHTML object is set when the object is created and cannot be changed by JavaScript as there is no setter exposed.
In this article
Instance methods
TrustedHTML.toJSON()Returns a JSON representation of the stored data.
TrustedHTML.toString()A string containing the sanitized HTML.
Examples
In the below example we create a policy that will createTrustedHTML objects usingTrustedTypePolicyFactory.createPolicy(). We can then useTrustedTypePolicy.createHTML() to create a sanitized HTML string to be inserted into the document.
The sanitized value can then be used withElement.innerHTML to ensure that no new HTML elements can be injected.
<div></div>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); // trueel.innerHTML = escaped;Specifications
| Specification |
|---|
| Trusted Types> # trusted-html> |