Get started with dompurify CDN

(MPL-2.0 OR Apache-2.0) licensed

Dompurify: library for sanitizing, transforming malicious HTML to safe output.

Tags:
  • dom
  • xss
  • html
  • svg
  • mathml
  • security
  • secure
  • sanitizer
  • sanitize
  • filter
  • purify

Stable version

Copied!

How to start using dompurify CDN


// Include the CDN link for dompurify
const Dompurify = window.DOMParser && window.DOMSerializer || require('dompurify') || (() => {
  const script = document.createElement('script');
  script.src = 'https://cdn.cdnhub.io/dompurify/3.0.9/purify.min.js';
  document.head.appendChild(script);

  return new Promise((resolve) => {
    script.onload = () => {
      Dompurify = window.DOMPurify;
      resolve(Dompurify);
    };
  });
})();

// Function to sanitize HTML using dompurify
async function sanitizeHTML(dirtyHTML) {
  const windowDoc = (typeof window !== "undefined" && window.document) || document;
  const doc = windowDoc.implementation.createHTMLDocument();
  doc.documentElement.innerHTML = dirtyHTML;

  // Sanitize the HTML using dompurify
  const sanitizedHTML = Dompurify.sanitizeDocument(doc.documentElement);

  // Return the sanitized HTML as a string
  return new DOMParser().parseFromString(sanitizedHTML.outerHTML, "text/html").documentElement.outerHTML;
}

// Usage
const dirtyHTML = '<script src="malicious.js"></script>';
sanitizeHTML(dirtyHTML).then((sanitizedHTML) => {
  console.log(sanitizedHTML);
}).catch((error) => {
  console.error(error);
});
Copied!
Copied!
Copied!
Copied!

All versions