Sanitizer: removeAttribute() 方法

可用性有限

此特性不是基線特性,因為它在一些最廣泛使用的瀏覽器中不起作用。

實驗性: 這是一項實驗性技術
在生產中使用此技術之前,請仔細檢查瀏覽器相容性表格

Sanitizer 介面的 removeAttribute() 方法將一個屬性設定為不允許在所有元素上使用。

指定的屬性會被新增到此 sanitier 配置的 removeAttributes 列表中。如果該屬性存在於 attributes 列表中,則會從中移除。

請注意,如果只想允許/不允許特定元素上的屬性,請使用 Sanitizer.allowElement()

語法

js
removeAttribute(attribute)

引數

attribute

一個字串,指示要全域性禁止在元素上使用的屬性的名稱,或者一個具有以下屬性的物件

name

包含屬性名稱的字串。

namespace 可選

一個包含屬性名稱空間的字串,預設為 null

返回值

無 (undefined)。

示例

如何禁止特定屬性

此示例顯示瞭如何使用 removeAttribute() 來指定應從元素中移除某個屬性。

JavaScript

程式碼首先建立一個新的 Sanitizer 物件,該物件最初不指定任何屬性或元素。然後,我們呼叫 removeAttribute() 並傳入屬性 titlemathcolor

js
// Create sanitizer that allows
const sanitizer = new Sanitizer({
  removeAttributes: [],
});

// Remove the title attribute
sanitizer.removeAttribute("title");
// Remove the mathcolor attribute
sanitizer.removeAttribute("mathcolor");

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

結果

最終配置將記錄在下方。請注意,這兩個屬性都已新增到 removeAttributes 列表中(當使用 sanitier 時,如果這些屬性存在於元素上,它們將被移除)。

規範

規範
HTML Sanitizer API
# dom-sanitizer-removeattribute

瀏覽器相容性