W3cubDocs

/Web APIs

Sanitizer: sanitize() method

Experimental: This is an experimental technology
Check the Browser compatibility table carefully before using this in production.

Secure context: This feature is available only in secure contexts (HTTPS), in some or all supporting browsers.

The sanitize() method of the Sanitizer interface is used to sanitize a tree of DOM nodes, removing any unwanted elements or attributes.

It should be used when the data to be sanitized is already available as DOM nodes. For example when sanitizing a Document instance in a frame.

The default Sanitizer() configuration strips out XSS-relevant input by default, including <script> tags, custom elements, and comments. The sanitizer configuration may be customized using Sanitizer() constructor options.

Note: To sanitize strings, instead use Element.setHTML() or Sanitizer.sanitizeFor(). See HTML Sanitizer API for more information.

Syntax

js

sanitize(input)

Parameters

input

A DocumentFragment or Document to be sanitized.

Return value

A sanitized DocumentFragment.

Exceptions

None.

Examples

To sanitize data from an iframe with id userFrame:

js

const sanitizer = new Sanitizer(); // Default sanitizer;

// Get the frame and its Document object
const frame_element = document.getElementById("userFrame");
const unsanitized_frame_tree = frame_element.contentWindow.document;

// Sanitize the document tree and update the frame.
const sanitized_frame_tree = sanitizer.sanitize(unsanitized_frame_tree);
frame_element.replaceChildren(sanitized_frame_tree);

Specifications

Browser compatibility

Desktop Mobile
Chrome Edge Firefox Internet Explorer Opera Safari WebView Android Chrome Android Firefox for Android Opera Android Safari on IOS Samsung Internet
sanitize 93–119 93–119 83 No 79 No No 93–119 No No No No

See also

© 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/API/Sanitizer/sanitize