Sanitizer: allowElement() 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.
TheallowElement() method of theSanitizer interface sets that the specified element is allowed in the output when the sanitizer is used.
It can also be used to specify per-element attribute allow or remove arrays onSanitizer instances with anallow configuration.
In this article
Syntax
allowElement(element)Parameters
elementA string indicating the name of the allowed element, or an object with the following properties:
nameA string containing the name of the element.
namespaceOptionalA string containing the namespace of the element.The default namespace is
"http://www.w3.org/1999/xhtml".attributesOptionalAn array indicating the attributes to allow on this (allowed) element when sanitizing HTML.
Each attribute can be specified by name (a string), or as an object with the following properties:
nameA string containing the name of the attribute.
namespaceOptionalA string containing the namespace of the attribute, which defaults to
null.
removeAttributesOptionalAn array indicating the attributes to remove on this (allowed) element when sanitizing HTML.
Each attribute can be specified by name (a string), or as an object with the following properties:
nameA string containing the name of the attribute.
namespaceOptionalA string containing the namespace of the attribute, which defaults to
null.
Return value
true if the operation changed the configuration to allow the element, andfalse if the configuration was not changed (usually because the element was already allowed, but potentially because the change could not be made).
Note thatfalse might be returned if the internal configuration:
- defines the
elementsarray and the element is already present (it does not need to be added again). - defines the
removeElementsarray and the specified element is not present (and is hence already not filtered). - defines the
removeElementsarray and attempts to allow an element with per-element attributes.This operation is not supported because in avalid configuration you can't have bothremoveElementsandelementsarrays, and per-element attributes are added in theelementsarray.The call won't change the configuration and will generate a console warning.
Description
TheallowElement() method sets that the specified element is allowed in the output when the sanitizer is used.
The method can be used with either anallow configuration or aremove configuration.If used with an allow configuration, the specified element is added to theelements array.If used with a remove configuration, the element is removed from theremoveElements array (if present).If present, it would also be removed from thereplaceWithChildrenElements array.
For example, the following code creates an allowSanitizer that allows<span> elements and then callsallowElement() to additionally allow<b> elements.
const sanitizer = new Sanitizer({ elements: ["span"] });sanitizer.allowElement("b");When using aSanitizer with an allow configuration you can also use the method to specify attributes to be allowed or disallowed on elements of that type.For example, the following code first creates an allow sanitizer configuration by specifying theelements array (creating aSanitizer with an empty object or no configuration object would also result in an "allow configuration").It then callsallowElement() to allowdiv elements, to allow theclass attribute on<div> elements, and to remove thelang attribute on<div> elements.
const sanitizer = new Sanitizer({ elements: ["span"] });sanitizer.allowElement({ name: "div", attributes: ["class"], removeAttributes: ["lang"],});If you need both per-element add-attribute and remove-attribute arrays as shown above, they must be added in a single call to this method.If you were to do this in two calls the second call would replace the element definition added in the first call.
When using aSanitizer with aremove configuration, similar code to add per-element attribute allow or remove arrays will generate a console warning and returnfalse.This is because internally the sanitizer doesn't have theelements array required to specify per-element attributes and won't change the configuration.
// Define Sanitizer with a remove configuration// by specifying removeElements in the configurationconst sanitizer = new Sanitizer({ removeElements: [] });// Returns false and raises a console warningsanitizer.allowElement({ name: "div", attributes: ["class"], removeAttributes: ["lang"],});Examples
>How to allow elements
This example shows howallowElement() is used to add an element to the sanitizer'selements configuration (the list of allowed elements).
<pre></pre>#log { height: 400px; overflow: scroll; padding: 0.5rem; border: 1px solid black;}const logElement = document.querySelector("#log");function log(text) { logElement.textContent = text;}JavaScript
The code first creates a newSanitizer object that initially allows<div> and<script> elements.It then callsallowElement() to add a<p> element specified as a string parameter, and then again to add a<span> element specified as an object.We then get and log the configuration.
if ("Sanitizer" in window) {// Create sanitizer using SanitizerConfigconst sanitizer = new Sanitizer({ elements: ["div", "script"],});// Allow <p> specifying a stringsanitizer.allowElement("p");// Allow <span> specifying an objectsanitizer.allowElement({ name: "span" });let sanitizerConfig = sanitizer.get();log(JSON.stringify(sanitizerConfig, null, 2));} else { log("The HTML Sanitizer API is NOT supported in this browser.");}Results
The final configuration is logged below.This includes the original elements (<div> and<script>) and the two added withallowElement() (<p> and<span>).
Allowing elements that are already allowed or removed
This example shows the effect of usingallowElement() to add elements that are already allowed, or that are in the configuration as "to be removed".
<pre></pre>#log { height: 400px; overflow: scroll; padding: 0.5rem; border: 1px solid black;}const logElement = document.querySelector("#log");function log(text) { logElement.textContent = text;}JavaScript
The code first creates a newSanitizer object that initially allows<div> elements (removing attributes other thanid) and also replaced<span> elements with any child elements.
It then callsallowElement(), firstly to add a<div> element that removesstyle attributes.Since the<div> element is already allowed, it is removed from theelements configuration and the<div> element definition is appended.
A<span> element is then added to the allow list, which removes it from thereplaceWithChildrenElements configuration list.
if ("Sanitizer" in window) {// Create sanitizer using SanitizerConfigconst sanitizer = new Sanitizer({ elements: [{ name: "div", attributes: [{ name: "id" }] }], replaceWithChildrenElements: ["span"],});// Allow <div> elements.// Allow id elements but strip their style attributessanitizer.allowElement({ name: "div", removeAttributes: ["style"],});// Allow <span> elementssanitizer.allowElement("span");let sanitizerConfig = sanitizer.get();log(JSON.stringify(sanitizerConfig, null, 2));} else { log("The HTML Sanitizer API is NOT supported in this browser.");}Results
The final configuration is logged, and is shown below.From the log we can see that the original filter for the<div> element has been removed and the new definition appended to theelements list.Adding the<span> element to theelements list has removed it from thereplaceWithChildrenElements list.
Specifications
| Specification |
|---|
| HTML Sanitizer API> # dom-sanitizer-allowelement> |