Element: replaceWithHTMLUnsafe() method
Limited availability
This feature is not Baseline because it does not work in some of the most widely-used browsers.
Want more browser support for this feature? Tell us why.
Warning: This method parses its input as HTML, writing the result into the DOM. APIs like this are known as injection sinks, and are potentially a vector for cross-site scripting (XSS) attacks, if the input originally came from an attacker.
You can mitigate this risk by always passing TrustedHTML objects instead of strings and enforcing trusted types.
See Security considerations of the unsafe methods for more information.
Note:
Element.replaceWithHTML() should almost always be used (where supported) instead of this method as it is always XSS-safe.
The replaceWithHTMLUnsafe() method of the Element interface is used to parse HTML input into a DocumentFragment and insert it into the DOM as a replacement of the Element. The method may optionally sanitize the input while parsing it.
Syntax
replaceWithHTMLUnsafe(input)
replaceWithHTMLUnsafe(input, options)
Parameters
input-
A
TrustedHTMLinstance or string defining HTML to be parsed. optionsOptional-
An options object with the following optional parameters:
sanitizerOptional-
A
SanitizerorSanitizerConfigobject that defines which elements, attributes, comments, and processing instructions of the input will be allowed or removed. This can also be a string with the value"default", which applies aSanitizerwith the (XSS-safe) default sanitizer configuration. If not specified, no sanitizer is used.Note that if you're using the same configuration multiple times, it's expected to be more efficient to use a
Sanitizerand modify it when you need to. runScriptsOptional-
A boolean value indicating whether any scripts included in the newly inserted HTML should run after inserting. The default is
false.
Return value
None (undefined).
Exceptions
TypeError-
This is thrown if:
inputis passed a string when Trusted Types are enforced by a CSP and no default policy is defined.options.sanitizeris passed a:SanitizerConfigthat isn't valid. For example, a configuration that includes bothelementsandremoveElementsconfiguration settings.- string that does not have the value
"default". - value that is not a
Sanitizer,SanitizerConfig, or string.
options.runScriptsistrueoroptions.sanitizeris specified when Trusted Types are enforced and no default policy definescreateParserOptions— even if input is aTrustedHTML. (Passing aTrustedHTMLParserOptionsas options avoids this.)
HierarchyRequestErrorDOMException-
Thrown when the parent node is a
Document, an<html>element, a<template>element, or a hostlessDocumentFragment. Note this differs fromElement.insertAdjacentHTMLwhich throwsNoModificationAllowedErrorfor aDocumentparent.
Description
The replaceWithHTMLUnsafe() method is used to parse HTML input into a DocumentFragment and insert it into the DOM as a replacement of the Element. The method may optionally sanitize the input while parsing it.
The method does nothing if the node has no parent.
The method uses context-aware HTML parsing, which may discard or rearrange elements depending on the parsing context (for example, a <col> element outside of a <table>).
Like all unsafe HTML setters, it will not remove additional items from its input, unless it is passed a sanitizer that removes them. However, it does not run scripts by default unless runScripts: true is provided as an option.
Unlike with Element.innerHTML, declarative shadow roots in the input will be parsed into the DOM.
If the string of HTML defines more than one declarative shadow root in a particular shadow host then only the first ShadowRoot is created — subsequent declarations are parsed as <template> elements within that shadow root.
Security considerations
The suffix "Unsafe" in the method name indicates that it does not enforce removal of all XSS-unsafe HTML elements and attributes. This has extra security considerations as detailed in the sanitizer API "Security considerations of the unsafe methods" section and "When should the unsafe methods be used?" section.
Examples
Note:
The setHTMLUnsafe() page includes additional examples, including a live example, which are similar to how replaceWithHTMLUnsafe() can be used.
replaceWithHTMLUnsafe() with Trusted Types
To mitigate the risk of XSS, we'll first create a TrustedHTML object from the string containing the HTML, and then pass that object to replaceWithHTMLUnsafe().
Since trusted types are not yet supported on all browsers, we define the trusted types tinyfill.
This acts as a transparent replacement for the Trusted Types JavaScript API:
if (typeof trustedTypes === "undefined")
trustedTypes = { createPolicy: (n, rules) => rules };
Next we create a TrustedTypePolicy that defines a createHTML() for transforming an input string into TrustedHTML instances.
Commonly implementations of createHTML() use a library such as DOMPurify to sanitize the input as shown below:
const policy = trustedTypes.createPolicy("my-policy", {
createHTML: (input) => DOMPurify.sanitize(input),
});
Then we use this policy object to create a TrustedHTML object from the potentially unsafe input string:
// The potentially malicious string
const untrustedString = "abc <script>alert(1)<" + "/script> def";
// Create a TrustedHTML instance using the policy
const trustedHTML = policy.createHTML(untrustedString);
Now that we have trustedHTML, the code below shows how you can use it with replaceWithHTMLUnsafe().
The input has been through the transformation function, so we don't pass a sanitizer to the method.
// Get the target Element with id "target"
const target = document.getElementById("target");
// replaceWithHTMLUnsafe() with no sanitizer
target.replaceWithHTMLUnsafe(trustedHTML);
Using replaceWithHTMLUnsafe() without Trusted Types
This example demonstrates the case where we aren't using trusted types, so we'll be passing sanitizer arguments.
The code creates an untrusted string and shows a number of ways a sanitizer can be passed to the method.
// The potentially malicious string
const untrustedString = "abc <script>alert(1)<" + "/script> def";
// Get the target Element with id "target"
const target = document.getElementById("target");
// Define custom Sanitizer and use in replaceWithHTMLUnsafe()
// This allows only elements: div, p, button, script
const sanitizer1 = new Sanitizer({
elements: ["div", "p", "button", "script"],
});
target.replaceWithHTMLUnsafe(untrustedString, { sanitizer: sanitizer1 });
// Define custom SanitizerConfig within replaceWithHTMLUnsafe()
// Removes the <script> element but allows other potentially unsafe elements and attributes.
target.replaceWithHTMLUnsafe(untrustedString, {
sanitizer: { removeElements: ["script"] },
});
Using replaceWithHTMLUnsafe() with runScripts
This example demonstrates the case when we allow scripts to run using the runScripts option. This should be used with care.
// HTML from a trusted source
const htmlString = "<script src='example.js'></script><p>Other content</p>";
// Get the target Element with id "target"
const target = document.getElementById("target");
// No sanitizer is passed, so the <script> element is kept
// and also executes the script after insertion.
target.replaceWithHTMLUnsafe(htmlString, {
runScripts: true,
});
Specifications
| Specification |
|---|
| HTML> # dom-nondocumenttypechildnode-replacewithhtmlunsafe> |