Sanitizer: removeUnsafe() method
Experimental: This is an experimental technology
Check the Browser compatibility table carefully before using this in production.
The removeUnsafe()
method of the Sanitizer
interface configures the sanitizer configuration so that it will remove all elements, attributes, and event handler content attributes that are considered XSS-unsafe by the browser.
The unsafe elements and attributes are added to the configuration by calling Sanitizer.removeElement()
and Sanitizer.removeAttribute()
for each, respectively.
This adds them to the sanitizer configuration disallow lists: removeElements
and removeAttributes
, and removes them (if present) from the configuration allow lists: elements
, replaceWithChildrenElements
and attributes
.
The method can be called to make any custom configuration XSS-safe. If used with a configuration that uses the allow lists, it will remove the XSS-unsafe entities from those lists. If used with a configuration that uses only the disallow ("remove") lists, then it ensures the configuration includes the unsafe elements in those lists.
Note that if you're using the sanitizer with one of the "safe" HTML setters, such as Element.setHTML()
and ShadowRoot.setHTML()
, you do not need to call this method to make the sanitizer safe.
When used in these setters the method is called implicitly, without modifying the Sanitizer
instance that is passed.
Syntax
removeUnsafe()
Parameters
None.
Returns
None (undefined
).
Examples
Basic usage
The following code shows how removeUnsafe()
is used.
// Create sanitizer.
const sanitizer = new Sanitizer(/* Some configuration */);
// Make the configuration XSS-safe
sanitizer.removeUnsafe();
Making a sanitizer configuration safe
This example demonstrates how calling removeUnsafe()
makes the sanitizer configuration XSS-safe.
JavaScript
The code first creates a new Sanitizer
object that that allows the safe element <p>
, the unsafe elements <script>
and <iframe>
, and the unsafe onwebkitanimationend
event handler attribute.
The code then calls removeUnsafe()
on the sanitizer and logs its configuration.
// Create sanitizer that allows
const sanitizer = new Sanitizer({
elements: ["p", "script"],
attributes: ["onwebkitanimationend"],
replaceWithChildrenElements: ["iframe"],
});
// Make the sanitizer safe!
sanitizer.removeUnsafe();
// Log the sanitizer configuration
const sanitizerConfig = sanitizer.get();
log(JSON.stringify(sanitizerConfig, null, 2));
Results
The resulting configuration is shown below.
Note how the unsafe elements and attributes have been removed from the "allow" lists to the corresponding "remove" lists.
In this case we still have <p>
in the allowed elements, so only <p>
elements in the input will be imported when the sanitizer is used.
Specifications
Specification |
---|
HTML Sanitizer API # dom-sanitizer-removeunsafe |