How to render <style> tag using DOMPurify

4.4k Views Asked by At

In our application for a very specific scenario (at only one place) we need to bypass the tag and render it on the DOM using DOMPurify.

var htmlScript = "<style>*{color: red}</style>"; // something like this
var clean = dompurify.sanitize(htmlScript, { ADD_TAGS: ['style']});
return clean;

Does anyone know how to achieve it ?

1

There are 1 best solutions below

0
On

I believe you can do that with these 3 options: FORCE_BODY, ALLOWED_TAGS, and ALLOWED_ATTR.

Example:

outHtml = domPurify.sanitize(outHtml, {
    FORCE_BODY: true,
    ALLOWED_ATTR: ['style', 'class', 'type', 'href', 'rel'],
    // must add these tag manually if use this option.
    ALLOWED_TAGS: [
      'link',
      'figure',
      'table',
      'caption',
      'thead',
      'tr',
      'th',
      'tbody',
      'td',
    ],
  });