Movatterモバイル変換


[0]ホーム

URL:


  1. Web
  2. Web APIs
  3. Element
  4. setHTML()

Element: setHTML() method

Limited availability

This feature is not Baseline because it does not work in some of the most widely-used browsers.

Experimental:This is anexperimental technology
Check theBrowser compatibility table carefully before using this in production.

ThesetHTML() method of theElement interface provides an XSS-safe method to parse and sanitize a string of HTML and insert it into the DOM as a subtree of the element.

The method removes any elements and attributes that are considered XSS-unsafe, even if allowed by a passed sanitizer.Notably, the following elements are always removed:<script>,<frame>,<iframe>,<embed>,<object>,<use>, and event handler attributes.

It is recommended (if supported) as a drop-in replacement forElement.innerHTML when setting a user-provided string of HTML.

Syntax

js
setHTML(input)setHTML(input, options)

Parameters

input

A string defining HTML to be sanitized and injected into the element.

optionsOptional

An options object with the following optional parameters:

sanitizer

ASanitizer orSanitizerConfig object which defines what elements of the input will be allowed or removed, or the string"default" for the default configuration.The method will remove any XSS-unsafe elements and attributes, even if allowed by the sanitizer.

Note that generally aSanitizer is expected to be more efficient than aSanitizerConfig if the configuration is to be reused.If not specified, the default sanitizer configuration is used.

Return value

None (undefined).

Exceptions

TypeError

This is thrown ifoptions.sanitizer is passed a:

  • non-normalizedSanitizerConfig (one that includes both "allowed" and "removed" configuration settings).
  • string that does not have the value"default".
  • value that is not aSanitizer,SanitizerConfig, or string.

Description

ThesetHTML() method provides an XSS-safe method to parse and sanitize a string of HTML into aDocumentFragment, and then insert it into the DOM as a subtree of the element.

setHTML() drops any elements in the HTML input string that are invalid in the context of the current element, such as a<col> element outside of a<table>.It then removes any HTML entities that aren't allowed by the sanitizer configuration, and further removes any XSS-unsafe elements or attributes — whether or not they are allowed by the sanitizer configuration.

If no sanitizer configuration is specified in theoptions.sanitizer parameter,setHTML() is used with the defaultSanitizer configuration.This configuration allows all elements and attributes that are considered XSS-safe, thereby disallowing entities that are considered unsafe; see theSanitizer() constructor for more information.A custom sanitizer or sanitizer configuration can be specified to choose which elements, attributes, and comments are allowed or removed.Note that even if unsafe options are allowed by the sanitizer configuration, they will still be removed when using this method (which implicitly callsSanitizer.removeUnsafe()).

setHTML() should be used instead ofElement.innerHTML for inserting untrusted strings of HTML into an element.It should also be used instead ofElement.setHTMLUnsafe(), unless there is a specific need to allow unsafe elements and attributes.

Note that since this method always sanitizes input strings of XSS-unsafe entities, it is not secured or validated using theTrusted Types API.

Examples

Basic usage

This example shows some of the ways you can usesetHTML() to sanitize and inject a string of HTML.

js
// Define unsanitized string of HTMLconst unsanitizedString = "abc <script>alert(1)<" + "/script> def";// Get the target Element with id "target"const target = document.getElementById("target");// setHTML() with default sanitizertarget.setHTML(unsanitizedString);// Define custom Sanitizer and use in setHTML()// This allows only elements: div, p, button (script is unsafe and will be removed)const sanitizer1 = new Sanitizer({  elements: ["div", "p", "button", "script"],});target.setHTML(unsanitizedString, { sanitizer: sanitizer1 });// Define custom SanitizerConfig within setHTML()// This removes elements div, p, button, script, and any other unsafe elements/attributestarget.setHTML(unsanitizedString, {  sanitizer: { removeElements: ["div", "p", "button", "script"] },});

setHTML() live example

This example provides a "live" demonstration of the method when called with different sanitizers.The code defines buttons that you can click to sanitize and inject a string of HTML using a default and a custom sanitizer, respectively.The original string and sanitized HTML are logged so you can inspect the results in each case.

HTML

The HTML defines two<button> elements for applying different sanitizers, another button to reset the example, and a<div> element to inject the string into.

html
<button type="button">Default</button><button type="button">allowScript</button><button type="button">Reload</button><div>Original content of target element</div>
<pre></pre>
#log {  height: 320px;  overflow: scroll;  padding: 0.5rem;  border: 1px solid black;  margin: 5px;}

JavaScript

const logElement = document.querySelector("#log");function log(text) {  logElement.textContent += text;}
if ("Sanitizer" in window) {

First we define the string to sanitize, which will be the same for all cases.This contains the<script> element and theonclick handler, both of which are considered XSS-unsafe.We also define the handler for the reload button.

js
// Define unsafe string of HTMLconst unsanitizedString = `  <div>    <p>Paragraph to inject into shadow DOM.      <button>Click me</button>    </p>    <script src="path/to/a/module.js" type="module"><\/script>    <p data-id="123">Para with <code>data-</code> attribute</p>  </div>`;const reload = document.querySelector("#reload");reload.addEventListener("click", () => document.location.reload());

Next we define the click handler for the button that sets the HTML with the default sanitizer.This should strip out all unsafe entities before inserting the string of HTML.Note that you can see exactly which elements are removed in theSanitizer() constructor examples.

js
const defaultSanitizerButton = document.querySelector("#buttonDefault");defaultSanitizerButton.addEventListener("click", () => {  // Set the content of the element using the default sanitizer  target.setHTML(unsanitizedString);  // Log HTML before sanitization and after being injected  logElement.textContent =    "Default sanitizer: remove script element, onclick attribute, data- attribute\n\n";  log(`\nunsanitized: ${unsanitizedString}`);  log(`\n\nsanitized: ${target.innerHTML}`);});

The next click handler sets the target HTML using a custom sanitizer that allows only<div>,<p>, and<script> elements.Note that because we're using thesetHTML method,<script> will also be removed!

js
const allowScriptButton = document.querySelector("#buttonAllowScript");allowScriptButton.addEventListener("click", () => {  // Set the content of the element using a custom sanitizer  const sanitizer1 = new Sanitizer({    elements: ["div", "p", "script"],  });  target.setHTML(unsanitizedString, { sanitizer: sanitizer1 });  // Log HTML before sanitization and after being injected  logElement.textContent =    "Sanitizer: {elements: ['div', 'p', 'script']}\n Script removed even though allowed\n";  log(`\nunsanitized: ${unsanitizedString}`);  log(`\n\nsanitized: ${target.innerHTML}`);});
} else {  log("The HTML Sanitizer API is NOT supported in this browser.");  // Provide fallback or alternative behavior}

Results

Click the "Default" and "allowScript" buttons to see the effects of the default and custom sanitizer, respectively.

Note that because we are using a safe sanitization method, in both cases the<script> element andonclick handler are removed, even if explicitly allowed by the sanitizer.However while thedata- attribute is removed with the default sanitizer, it is allowed when we pass a sanitizer.

Specifications

Specification
HTML Sanitizer API
# dom-element-sethtml

Browser compatibility

See also

Help improve MDN

Learn how to contribute

This page was last modified on byMDN contributors.


[8]ページ先頭

©2009-2025 Movatter.jp