Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to render <style> tag using DOMPurify

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 ?

like image 755
YepMe Avatar asked Feb 04 '26 04:02

YepMe


1 Answers

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',
    ],
  });
like image 107
namdo Hoag Avatar answered Feb 06 '26 16:02

namdo Hoag



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!