You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Commit 6a92efd
Browse filesBrowse the repository at this point in the historyBrowse files
feat!: sanitize with DOMPurify by default and add a React Native entry
The default entry now sanitizes the parsed tree in place with a private
DOMPurify instance, so what DOMPurify checked is exactly what renders. On
top of DOMPurify's defaults it only removes what reaches past the fragment:
<style> and <title>, form/formaction, position: fixed styles and
javascript: attribute values. A new `purify` option merges a DOMPurify
config over the built-in one, and DOMPurify still runs after a caller's
own `sanitize`.
A new `react-html5-parser/core` entry keeps the unsanitized parser at
about 3 kB, and `react-html5-parser/native` renders HTML to React Native
View, Text and Image components. It parses with htmlparser2, bundled into
the entry so Metro versions that ignore package exports can resolve it,
opens links only for http, https, mailto and tel, and loads images only
from http, https and raster data URIs.
The parser was audited against React 18 and 19: SVG attributes are mapped
by default, form fields stay uncontrolled, React 19 head hoisting and
<html>/<body> binding are avoided, and custom elements keep their
attribute names.
BREAKING CHANGE: react >= 18 is now required (react-native >= 0.71 for the
native entry). `parse` from the default entry sanitizes, which grows it to
about 15 kB; import from `react-html5-parser/core` to opt out. Entries in
`components` render as React components rather than being called as
functions, so an inline arrow function remounts its subtree on every
render.
-`components` (`object?`): Override React elements. The keys are HTML equivalents (such as `div`)
47
+
-`purify` (`object?`): DOMPurify config for the default entry, see below
48
+
-`sanitize` (`function?`): Transform or sanitize the HTML string before parsing. On the default entry DOMPurify still runs after it
49
+
-`components` (`object?`): Override React elements. The keys are lowercase HTML tag names (such as `div`). Each value is rendered as a React component, so it may use hooks
44
50
-`mapNode` (`function?`): Override Dom node
45
-
-`mapElement` (`function?`): Override React element. Сalled after `components` override
51
+
-`mapElement` (`function?`): Override React element. Called after `components` override; for an overridden tag it receives the component element (`element.type` is the component)
46
52
-`attrsMap` (`object?`): Map for converting dom attributes to react attributes
47
53
-`onError` (`function?`): Listen errors, if we provide not a string `html` or catch an unexpected internal error
48
54
49
55
#### Return
50
56
51
57
Return `React.Fragment | null`. We get `null` if html is not a string or catch an unexpected internal error
52
58
53
-
### sanitize `(html: string) => string`
59
+
### Built-in sanitizer
60
+
61
+
`parse` from `react-html5-parser` sanitizes with [DOMPurify](https://github.com/cure53/DOMPurify). It runs on the parsed DOM tree in place, not on a string, so the tree DOMPurify checked is exactly the tree that gets rendered: no second parse and no mutation XSS. It uses a private DOMPurify instance, so an app's own DOMPurify setup and hooks are not affected.
62
+
63
+
On top of DOMPurify's defaults (no scripts, event handlers, `javascript:` URLs, frames, embeds or DOM clobbering ids), it removes only what reaches past the parsed fragment:
64
+
65
+
-`<style>` and `<title>`, which act on the whole page;
66
+
-`form` and `formaction`, which submit the page's own form to another site;
67
+
- a `style` attribute that sets `position: fixed`, which can lay content over the whole page;
68
+
- any attribute whose value is a `javascript:` URL.
69
+
70
+
It keeps `target` on links and sets `rel="noopener noreferrer"` with it. DOMPurify's allowlist still drops attributes such as `contenteditable` and `fetchpriority`.
71
+
72
+
Unknown and custom elements are removed and their content is kept, except tags you map in `components`: those are allowed. A mapped custom element (`x-card`) also keeps its custom attributes as props, without event handlers or `javascript:` values.
73
+
74
+
Limits worth knowing:
75
+
76
+
- CSS can still move content outside its box (`position: absolute`, negative margins, transforms). Put `contain: paint` on the element that holds the parsed HTML to clip it.
77
+
- Attributes such as `popovertarget` and `commandfor` stay, and can open the page's own popovers and dialogs by id. Forbid them through `purify` if that matters.
78
+
- An `id` such as `APP_CONFIG` still becomes `window.APP_CONFIG` when the page defines no global of that name. Do not read optional globals from `window` on pages that render user HTML.
79
+
80
+
### purify `DOMPurify.Config`
81
+
82
+
Default entry only. Merged over the built-in config, so each key you pass replaces the built-in one; `ADD_TAGS` is combined with the tags mapped in `components`.
The tree is always sanitized in place, so `IN_PLACE`, `RETURN_DOM`, `RETURN_DOM_FRAGMENT`, `RETURN_TRUSTED_TYPE` and `WHOLE_DOCUMENT` are ignored. The `position: fixed`, `javascript:` and `rel="noopener"` checks run whatever the config says.
On the default entry, DOMPurify runs after your `sanitize`, so a function that only trims or rewrites the HTML never turns sanitizing off. Use the core entry to replace DOMPurify.
React Native has no DOM, so this entry parses with [htmlparser2](https://github.com/fb55/htmlparser2), bundled into the entry so it also works with Metro versions that ignore package `exports`. Tags become native components:
203
+
204
+
- Block tags (`p`, `div`, `h1`–`h6`, `blockquote`, `pre`, `ul`, `ol`, `li`, `table`, `tr`, `td`, `hr`, …) become `View`. Their text is wrapped in `Text`, since React Native throws on a string directly inside a `View`.
205
+
- Inline tags (`b`, `strong`, `i`, `em`, `u`, `s`, `code`, `span`, `a`, …) become nested `Text`. A block inside inline content becomes `Text` too, on a line of its own.
206
+
-`img` becomes `Image`. Give it `width` and `height` in pixels: without both it takes the full width at a 16:9 ratio. Inside text, such as in a link, React Native shows an image only with both set.
207
+
-`br` becomes a line break. Whitespace collapses as in HTML, except inside `pre`.
208
+
- Unknown tags render only their content.
209
+
210
+
Options: `components`, `mapElement`, `sanitize` and `onError` work as on the web, plus:
211
+
212
+
-`tagStyles` (`{ [tag]: { view?, text?, image? } }`): merged over the default style of each tag.
213
+
-`textStyle`: the base style of all text.
214
+
-`onLinkPress` (`(href: string) => void`): handles every link tap, relative links included. You are responsible for checking the URL.
215
+
216
+
`components` receives the tag's attributes as props, except `style` (CSS text, which React Native rejects), `key`, `ref` and `children`, and the rendered children.
217
+
218
+
There is no script engine, so the native sanitizer guards what React Native can reach:
219
+
220
+
- links open through `Linking` only for `http:`, `https:`, `mailto:` and `tel:`; any other scheme, including app schemes and `intent:`, renders as plain text;
221
+
- images load only from `http:`, `https:` and base64 PNG, JPEG, GIF or WebP data URIs;
222
+
-`script`, `style`, `iframe`, `object`, `embed`, `svg`, `math`, `video`, `audio`, form controls and `head` content are dropped, as is any element with `hidden`;
223
+
-`style` attributes are ignored, so injected markup cannot overlay the app.
224
+
225
+
Remote images still reveal the reader's IP address to the image host. Map `img` in `components` to block or proxy them.
226
+
227
+
## Errors
228
+
229
+
`parse` never throws for bad input. It returns `null` and calls `onError(error, html)` when:
230
+
231
+
-`html`, or the result of `sanitize`, is not a string (`TypeError`);
232
+
-`sanitize`, `mapNode` or `mapElement` throws;
233
+
- there is no DOM, e.g. on the server (`ReferenceError`);
234
+
- the HTML nests deeper than the call stack allows (`RangeError`; browsers cap parser depth at about 512, so this only shows up outside them).
235
+
236
+
An error thrown inside `onError` reaches the caller. A component from `components` renders later, inside React, so its errors go to the nearest error boundary, not to `onError`.
237
+
238
+
## Notes
239
+
240
+
- HTML is parsed inside a `<template>` element, so scripts never run and images never load while parsing.
241
+
-`key`, `ref` and `children` attributes are ignored, since React would read them as its own props.
242
+
- Form fields stay uncontrolled: `value` / `checked` on `<input>`, the text of a `<textarea>` and the `selected` options of a `<select>` become `defaultValue` / `defaultChecked`. A file input's `value` is dropped, since React throws on it.
243
+
-`<noscript>` content is parsed as text, as browsers do while scripting is enabled.
244
+
-`hidden="until-found"` becomes plain `hidden`: React 19 treats `hidden` as a boolean.
245
+
- In the core entry, `async` is dropped from `<script>`, so React 19 renders it inert instead of hoisting and running it, and `<title>`, `<meta>` and `<link>` are hoisted into the document `<head>` by React 19.
0 commit comments