Skip to content
ФреймворкJavaScript

Sanitizer API: как очищается контент

Очистка HTML-контента для защиты от XSS-атак. В `static get sanitize()` инструмента поле данных можно сопоставить со строкой `'plaintext'` вместо карты тегов — это помечает поле как литеральный исходный текст, а не разметку.

Как получить экземпляр редактора

Методы ниже вызываются на редакторе, созданном через new Blok(). Они доступны после того, как разрешится editor.isReady.

TypeScript
// You already hold the instance returned by the constructor.
const editor = new Blok({ holder: 'editor' });
await editor.isReady;

// Call any API method on it.
editor.caret.setToLastBlock('end');

Методы

sanitizer.clean(taintString, config)

string

Clean HTML string using the provided sanitizer configuration. `'plaintext'` entries are field-level directives, not tag rules, so `clean()` filters them out of the config before parsing.

Когда использовать

Удаляет нежелательный HTML по набору правил перед вставкой внешнего контента — защита при вставке и импорте строк.

TypeScript
const dirtyHtml = '<script>alert("xss")</script><p>Hello</p>';
const clean = editor.sanitizer.clean(dirtyHtml, {
  p: true,  // Allow <p> tags
  b: true   // Allow <b> tags
});
// Returns: '<p>Hello</p>' (script tag removed)

Свойства

СвойствоТипОписание
plaintext'plaintext'A field-level sanitizer rule a tool declares in `static get sanitize()`, and part of the `SanitizerRule` union exported from the package root. Sanitization is an HTML parse: it entity-encodes bare `<`/`&` and drops text shaped like a stray end tag — irrecoverable corruption for a field holding literal source text, such as a code block's `code`. A field marked `'plaintext'` skips tag sanitization, the URL-scheme pass and the editor-level global sanitizer, and round-trips byte-identical. It is declared as a plain string literal rather than a Symbol, so tool sanitize configs survive JSON and `structuredClone`.
TypeScript
// A tool declares which of its data fields are markup and which are literal text
class CodeTool {
  static get sanitize() {
    return {
      code: 'plaintext',            // literal source — never HTML-parsed
      caption: { b: true, i: true } // markup — sanitized against these tags
    };
  }
}