[ Web Proxy ]
URL:
Viewing: https://developer.mozilla.org/ja/docs/Web/API/Element/setHTML [Back]  [Original]

Element: setHTML() - Web API | MDN

MDN Web Docs

View in English Always switch to English

Element: setHTML()

Want more browser support for this feature? Tell us why.

Experimental:

setHTML() Element HTML DocumentFragment DOM XSS

js
setHTML(input)
setHTML(input, options)

input

HTML

options

sanitizer

Sanitizer SanitizerConfig "default" SanitizerConfigSanitizer

(undefined)

TypeError

options.sanitizer

setHTML() HTML DocumentFragment DOM XSS

setHTML() <table> <col> HTML HTML XSS

options.sanitizer setHTML() Sanitizer XSS Sanitizer.removeUnsafe()

HTML Element.innerHTML setHTML() Element.setHTMLUnsafe()

XSS API

setHTML() HTML

js
// HTML 
const unsanitizedString = "abc <script>alert(1)<" + "/script> def";
// ID  "target" 
const target = document.getElementById("target");

// setHTML() 
target.setHTML(unsanitizedString);

//  setHTML() 
//  div, p, button script 
const sanitizer1 = new Sanitizer({
  elements: ["div", "p", "button", "script"],
});
target.setHTML(unsanitizedString, { sanitizer: sanitizer1 });

//  SanitizerConfig  setHTML() 
// divpbuttonscript/
target.setHTML(unsanitizedString, {
  sanitizer: { removeElements: ["div", "p", "button", "script"] },
});

setHTML()

HTML HTML

HTML

HTML 2 <button> <div>

html
<button id="buttonDefault" type="button"></button>
<button id="buttonAllowScript" type="button">allowScript</button>

<button id="reload" type="button"></button>
<div id="target"></div>

JavaScript

<script> onclick XSS

js
// HTML 
const unsanitizedString = `
  <div>
    <p>This is a paragraph. <button >Click me</button></p>
    <script src="path/to/a/module.js" type="module"><script>
  </div>
`;

const reload = document.querySelector("#reload");
reload.addEventListener("click", () => document.location.reload());

HTML HTML Sanitizer()

js
const defaultSanitizerButton = document.querySelector("#buttonDefault");
defaultSanitizerButton.addEventListener("click", () => {
  // 
  target.setHTML(unsanitizedString);

  //  HTML 
  logElement.textContent =
    "Default sanitizer: remove script element and onclick attribute\n\n";
  log(`\nunsanitized: ${unsanitizedString}`);
  log(`\nsanitized: ${target.innerHTML}`);
});

HTML <div><p><script> setHTML <script>

js
const allowScriptButton = document.querySelector("#buttonAllowScript");
allowScriptButton.addEventListener("click", () => {
  // 
  const sanitizer1 = new Sanitizer({
    elements: ["div", "p", "script"],
  });
  target.setHTML(unsanitizedString, { sanitizer: sanitizer1 });

  //  HTML 
  logElement.textContent =
    "Sanitizer: {elements: ['div', 'p', 'script']}\n Script removed even though allowed\n";
  log(`\nunsanitized: ${unsanitizedString}`);
  log(`\nsanitized: ${target.innerHTML}`);
});

allowScript <script> onclick

HTML
# dom-element-sethtml


Web Proxy Viewer  |  New URL  |  Original Page