Sanitizer

Module provides build-in methods for cleaning unwanted HTML tags and attributes. 

Available methods

clean Clean up passed string with specified rules

Sanitizer rules configuration

The example of sanitizer configuration:

const sanitizerConfig = { b: true, // leave <b> p: {}, // leave <p> without attributes }

Keys of config object is tags and the values is rules.

Rule

Rule can be boolean, object or function.

boolean Pass true to allow tag with all attributes, or false to remove tag
object Leave tag and sanitize attributes. Keys of object is attributes and values is rules. Pass {} to remove all attributes.
function Custom function that accept Element and returns a rule.

Examples

// leave <a> with only "href" attribute a: { href: true }
// leave <a> without attributes a: {}
// leave <b> if it does not contain 'bad text' b: function(el) { return !el.textContent.includes('bad text') }
// leave <a> with 'href' and add 'target="_blank"' for external links a: function(el) { const href = el.getAttribute('href') if (href && href.substring(0, 4) === 'http') { return { href: true, target: '_blank' } } else { return { href: true } } }
☝️
Advice.
Read more about configuration at the html-janitor page.

Clean

Perform sanitizing for passed HTML string with specified rules set.

Parametres

String Taint HTML string to sanitise
Object Sanitizer rules

Return value

String Sanitized HTML string

Example

const taintString = '<p>The <b style="color: red">Sanitizer</b> <a href="https://editorjs.io/sanitizer">module</a> represents a set of methods that clears taint strings.</p>'; const sanitizerConfig = { b: {}, // leave <b> without any attributes p: true, // leave <p> as is a: { href: true, // leave <a> with href target: '_blank' // add 'target="_blank"' } } /** * Perform sanitizing */ const cleanString = editor.sanitizer.clean(taintString, sanitizerConfing)