大网数据广告活动
Web 标准与前端开发

Sanitizer: Sanitizer() constructor

· 52CE 我爱测

The **`Sanitizer()`** constructor creates a new Sanitizer object, which can be used to filter unwanted elements and attributes from HTML or documents before they are inserted/parsed into the DOM.

HTML Sanitizer API

The Sanitizer() constructor creates a new Sanitizer object, which can be used to filter unwanted elements and attributes from HTML or documents before they are inserted/parsed into the DOM.

Syntax

new Sanitizer()
new Sanitizer(configuration)

Parameters

Returns

An instance of the Sanitizer object.

Exceptions

  • TypeError
    • : The configuration parameter is passed one of the following:
      • a SanitizerConfig that isn't a valid configuration. For example, a configuration that includes both "allowed" and "removed" configuration settings.
      • a string that does not have the value "default".

Description

The constructor creates a new Sanitizer object, which can be used to filter unwanted elements and attributes from HTML or documents before they are inserted/parsed into the DOM.

The default sanitizer configuration is an allow sanitizer that omits XSS-unsafe elements and attributes, along with other elements and attributes that can potentially be used in other attacks, such as clickjacking and spoofing. This configuration is suitable for the majority of sanitization use cases. It is created if "default" or no object is passed to the constructor.

The constructor can be passed a SanitizerConfig with a valid configuration to customize the sanitizer behavior.

A valid configuration can specify either elements or removeElements arrays (but not both) and either the attributes or removeAttributes arrays (but not both). In most cases it does not matter which of these arrays you use because, for example, the Sanitizer/allowAttribute method can implement the same behavior by adding the attribute to the attributes array or by removing it from the removeAttributes array. The main thing to note is that if you have a configuration with removeElements then you cannot have per-element attributes, as these must be defined on the elements array.

Examples

Creating the default sanitizer

This example shows how you can create the default Sanitizer and logs the resulting configuration object.

<pre id="log"></pre>
#log {
  height: 400px;
  overflow: scroll;
  padding: 0.5rem;
  border: 1px solid black;
}

JavaScript

The code first tests whether the Sanitizer interface is supported. It then creates the default Sanitizer, passing no options, and then gets and logs the configuration.

const logElement = document.querySelector("#log");
function log(text) {
  logElement.textContent = text;
}
if ("Sanitizer" in window) {
// Create default sanitizer
const sanitizer = new Sanitizer();

// Get and log the (default) configuration
const defaultConfig = sanitizer.get();
log(JSON.stringify(defaultConfig, null, 2));
} else {
  log("The HTML Sanitizer API is NOT supported in this browser.");
}

Results

The output is logged below. Note that the default configuration is an allow configuration, having both elements and attributes arrays that contain the elements that are allowed when the sanitizer is used.

Creating the default sanitizer

Creating a Sanitizer and using it with setHTML()

This example shows how you might create and use a custom sanitizer in a safe HTML DOM insertion method.

HTML

Here we define two pre elements in which we'll display both the sanitized and unsanitized HTML.

<pre id="unmodified"></pre>
<pre id="setHTML"></pre>
<pre id="log"></pre>
#log {
  height: 430px;
  overflow: scroll;
  padding: 0.5rem;
  border: 1px solid black;
}

JavaScript

const logElement = document.querySelector("#log");
function log(text) {
  logElement.textContent = text;
}

The following code tests whether the Sanitizer interface is supported. It then defines a string of "unsafe HTML", which contains bot safe elements, such as p and span, and XSS-unsafe elements such as script

We then create a Sanitizer object with a SanitizerConfig that allows the HTML elements: div, p, span, and script. The sanitizer is used with the unsafe string in Element.setHTML(). Both the original and sanitized strings are displayed as text nodes.

if ("Sanitizer" in window) {
// Define unsafe string of HTML
const unsafeHTMLString = `
  <div>
    <p>This is a paragraph. <span onclick="alert('You clicked the span!')">Click me</span></p>
    <script src="path/to/amodule.js" type="module"
  </div>
`;

// Set unsafe string as a text node of first element
const unmodifiedElement = document.querySelector("#unmodified");
unmodifiedElement.innerText = unsafeHTMLString;

// Create sanitizer using a SanitizerConfig that allows script (and other elements)
const sanitizer = new Sanitizer({ elements: ["div", "p", "span", "script"] });

// Use the sanitizer to set the HTML of the second element using the safe method
const setHTMLElement = document.querySelector("#setHTML");
setHTMLElement.setHTML(unsafeHTMLString, { sanitizer });

// Get that HTML and set it back to the element as a text node
// (so we can see the elements)
setHTMLElement.innerText = setHTMLElement.innerHTML;

// Log the configuration
const sanitizerConfig = sanitizer.get();
log(JSON.stringify(sanitizerConfig, null, 2));
} else {
  log("The HTML Sanitizer API is NOT supported in this browser.");
}

Results

The original string and sanitized HTML that was parsed into the DOM are shown below. Note that even though the sanitizer allows <script> elements, these are stripped out of the injected HTML when using Element.setHTML(). Also note that the configuration includes both the names of the elements and their namespaces.

Creating the default sanitizer

Specifications

Browser compatibility

来源:MDN Web Docs / Mozilla 贡献者 · 作者与贡献记录 · CC BY-SA 2.5。离线整理了版式、链接和媒体显示。

资料来源与适用范围

资料来源
MDN Web Docs / Mozilla 贡献者
适用范围
请按文中版本与环境说明核对
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 2.5

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。