Movatterモバイル変換


[0]ホーム

URL:


  1. Web
  2. Web APIs
  3. TrustedHTML

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.

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.

html
<div></div>
js
const escapeHTMLPolicy = trustedTypes.createPolicy("myEscapePolicy", {  createHTML: (string) => string.replace(/</g, "&lt;"),});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

Browser compatibility

See also

Help improve MDN

Learn how to contribute

This page was last modified on byMDN contributors.


[8]ページ先頭

©2009-2025 Movatter.jp