Sanitizer: allowAttribute() 方法

可用性有限

此特性不是基线特性,因为它在一些最广泛使用的浏览器中不起作用。

实验性: 这是一项实验性技术
在生产中使用此技术之前,请仔细检查浏览器兼容性表格

Sanitizer 接口的 allowAttribute() 方法用于允许某个属性出现在所有元素上。

指定的属性将被添加到此 sanitizer 配置的 attributes 列表中。如果该属性存在于 removeAttributes 列表中,它将被移除。

请注意,如果只想允许/禁止特定元素上的属性,请使用 Sanitizer.allowElement()

语法

js
allowAttribute(attribute)

参数

attribute

一个字符串,表示要全局允许在元素上使用的属性的名称,或者一个包含以下属性的对象

name

包含属性名称的字符串。

namespace 可选

一个包含属性命名空间的字符串,默认为 null

返回值

无 (undefined)。

示例

如何允许在元素上使用特定属性

此示例显示了如何使用 allowAttribute() 来指定某个属性在元素上是允许的。

JavaScript

代码首先创建一个新的 Sanitizer 对象,该对象最初不允许任何属性。然后,我们调用 allowAttribute() 方法,传入属性 titlemathcolor

js
// Create an allow sanitizer
const sanitizer = new Sanitizer({
  attributes: [],
});

// Allow the "title" attribute
sanitizer.allowAttribute("title");
// Allow the "mathcolor" attribute
sanitizer.allowAttribute("mathcolor");

// Log the sanitizer configuration
let sanitizerConfig = sanitizer.get();
log(JSON.stringify(sanitizerConfig, null, 2));

结果

最终配置将在下方打印。请注意,这两个属性都已添加到 attributes 列表中(当 sanitizer 被使用时,其他属性将不会被允许在元素上)。

规范

规范
HTML Sanitizer API
# dom-sanitizer-allowattribute

浏览器兼容性