Dompurify.sanitize don't allow script tag even I had added FORCE_BODY: true and ADD_TAGS:["script"]

1.9k views Asked by At

Please can anyone tell me what I did wrong here? What should I do to allow the script tag? My Html string data coming from database will be the same pattern as I showed here.

const cleanHtmlString = DOMPurify.sanitize("<body id=\"icoo\"><div id=\"ihl2v\"></div><form method=\"get\"></form><div id=\"ik9rs\" class=\"countdown\"><span data-js=\"countdown\" class=\"countdown-cont\"><div class=\"countdown-block\"><div data-js=\"countdown-day\" class=\"countdown-digit\"></div><div class=\"countdown-label\">days</div></div><div class=\"countdown-block\"><div data-js=\"countdown-hour\" class=\"countdown-digit\"></div><div class=\"countdown-label\">hours</div></div><div class=\"countdown-block\"><div data-js=\"countdown-minute\" class=\"countdown-digit\"></div><div class=\"countdown-label\">minutes</div></div><div class=\"countdown-block\"><div data-js=\"countdown-second\" class=\"countdown-digit\"></div><div class=\"countdown-label\">seconds</div></div></span><span data-js=\"countdown-endtext\" class=\"countdown-endtext\"></span></div><script>var items = document.querySelectorAll('#ik9rs');\n          for (var i = 0, len = items.length; i < len; i++) {\n            (function(){\nvar e=new Date(\"2022-05-27\").getTime(),t=this.querySelector(\"[data-js=countdown]\"),n=this.querySelector(\"[data-js=countdown-endtext]\"),r=this.querySelector(\"[data-js=countdown-day]\"),i=this.querySelector(\"[data-js=countdown-hour]\"),a=this.querySelector(\"[data-js=countdown-minute]\"),o=this.querySelector(\"[data-js=countdown-second]\"),s=this.gjs_countdown_interval;s&&s&&clearInterval(s);var l=function(e,t,n,s){r.innerHTML=e<10?\"0\"+e:e,i.innerHTML=t<10?\"0\"+t:t,a.innerHTML=n<10?\"0\"+n:n,o.innerHTML=s<10?\"0\"+s:s},u=function(){var r=(new Date).getTime(),i=e-r,a=Math.floor(i/864e5),o=Math.floor(i%864e5/36e5),s=Math.floor(i%36e4/6e4),u=Math.floor(i%6e4/1e3);l(a,o,s,u),i<0&&(clearInterval(c),n.innerHTML=\"EXPIRED\",t.style.display=\"none\",n.style.display=\"\")};if(e){var c=setInterval(u,1e3);this.gjs_countdown_interval=c,n.style.display=\"none\",t.style.display=\"\",u()}else l(0,0,0,0)\n}.bind(items[i]))();\n          }</script></body>", {
    FORCE_BODY: true,
    SAFE_FOR_TEMPLATES: true,
    
    ADD_TAGS: ["script", "iframe", ],
    ADD_ATTR: ["allow", "allowfullscreen", "frameborder", "scrolling", "data-js" ],
  });
  console.log(cleanHtmlString)

1

There are 1 answers

0
Visaka Devi On

The issue with your code is that you're using the SAFE_FOR_TEMPLATES flag which explicitly disallows the script tag, even if it's included in the ADD_TAGS list. To allow the script tag, you need to remove the SAFE_FOR_TEMPLATES flag and use the ALLOWED_TAGS and ALLOWED_ATTR options to specify the tags and attributes you want to allow.