How to allow svg elements using the new Sanitize api

402 views Asked by At

https://developer.mozilla.org/en-US/docs/Web/API/HTML_Sanitizer_API

Using the html sanitizer api, it is removing the 'svg' tag even though I am adding it to the allowed list. How can I allow 'svg' tags?

Currently using chrome 105.

const cfg = Sanitizer.getDefaultConfiguration();
cfg.allowCustomElements = true;
cfg.allowElements.push('svg');
cfg.allowElements.push('slot');
cfg.allowElements.push('path');
const sanitizer = new Sanitizer(cfg)
const str = `<button>
        <svg viewBox="0 0 24 24">
            <path d="M7.41,8.58L12,13.17L16.59,8.58L18,10L12,16L6,10L7.41,8.58Z"></path>
        </svg>
</button>`

const container = document.createElement('div')
container.setHTML(str, {sanitizer: sanitizer})

The sanitizer is removing the svg tag and everything inside. const hasSvg = cfg.allowElements.includes('svg'); // is returning true

1

There are 1 answers

3
Oleksandr On

This is an experimental feature and has very poor support. In addition, it only works with the HTTPS protocol. That is, you cannot work with it through a regular localhost. You have to wait a little longer for bold use.

Try the purify-html library instead. It works with the more common browser API, is very lightweight (MINIFIED + GZIPPED - 462 bytes!) and safely removes dangerous tags.