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.
This commit is contained in:
Alex Mayants
2020-06-16 01:37:52 +03:00
committed by GitHub
parent ca1b19a31b
commit 71d4e59505

View File

@@ -5,16 +5,18 @@ import { linkify } from "remarkable/linkify"
import DomPurify from "dompurify" import DomPurify from "dompurify"
import cx from "classnames" import cx from "classnames"
DomPurify.addHook("beforeSanitizeElements", function (current, ) { if (DomPurify.addHook) {
// Attach safe `rel` values to all elements that contain an `href`, DomPurify.addHook("beforeSanitizeElements", function (current, ) {
// i.e. all anchors that are links. // Attach safe `rel` values to all elements that contain an `href`,
// We _could_ just look for elements that have a non-self target, // i.e. all anchors that are links.
// but applying it more broadly shouldn't hurt anything, and is safer. // We _could_ just look for elements that have a non-self target,
if (current.href) { // but applying it more broadly shouldn't hurt anything, and is safer.
current.setAttribute("rel", "noopener noreferrer") if (current.href) {
} current.setAttribute("rel", "noopener noreferrer")
return current }
}) return current
})
}
function Markdown({ source, className = "", getConfigs }) { function Markdown({ source, className = "", getConfigs }) {
if (typeof source !== "string") { if (typeof source !== "string") {