From 71d4e5950587a3a741c49ed2c9065c75cdcf1f51 Mon Sep 17 00:00:00 2001 From: Alex Mayants Date: Tue, 16 Jun 2020 01:37:52 +0300 Subject: [PATCH] improvement: Call `DomPurify.addHook` only if it exists (#5428) On server-side execution `dompurify` exports factory function instead of a purifier instance. Because of this, server-side code that imports SwaggerUI (e.g. via `swagger-ui-react`) fails, since `DomPurify.addHook` does not exist. This affects universal rendering apps which share code between client-side and server-side. --- src/core/components/providers/markdown.jsx | 22 ++++++++++++---------- 1 file changed, 12 insertions(+), 10 deletions(-) diff --git a/src/core/components/providers/markdown.jsx b/src/core/components/providers/markdown.jsx index 73f835cf..51ba1c1b 100644 --- a/src/core/components/providers/markdown.jsx +++ b/src/core/components/providers/markdown.jsx @@ -5,16 +5,18 @@ import { linkify } from "remarkable/linkify" import DomPurify from "dompurify" import cx from "classnames" -DomPurify.addHook("beforeSanitizeElements", function (current, ) { - // Attach safe `rel` values to all elements that contain an `href`, - // i.e. all anchors that are links. - // We _could_ just look for elements that have a non-self target, - // but applying it more broadly shouldn't hurt anything, and is safer. - if (current.href) { - current.setAttribute("rel", "noopener noreferrer") - } - return current -}) +if (DomPurify.addHook) { + DomPurify.addHook("beforeSanitizeElements", function (current, ) { + // Attach safe `rel` values to all elements that contain an `href`, + // i.e. all anchors that are links. + // We _could_ just look for elements that have a non-self target, + // but applying it more broadly shouldn't hurt anything, and is safer. + if (current.href) { + current.setAttribute("rel", "noopener noreferrer") + } + return current + }) +} function Markdown({ source, className = "", getConfigs }) { if (typeof source !== "string") {