UNPKG

1.08 kBJSXView Raw
1/* eslint-disable no-eval
2 */
3const React = require('react');
4const PropTypes = require('prop-types');
5
6/**
7 * @arg {string} html the HTML from which to extract script tags.
8 */
9const extractScripts = html => {
10 if (typeof window === 'undefined' || !html) return () => {};
11
12 const regex = /<script\b[^>]*>([\s\S]*?)<\/script>/gim;
13 const scripts = [...html.matchAll(regex)].map(m => m[1].trim());
14
15 return () => scripts.map(js => window.eval(js));
16};
17
18class HTMLBlock extends React.Component {
19 constructor(props) {
20 super(props);
21 if ('scripts' in this.props) this.runScripts = extractScripts(this.props.html);
22 }
23
24 componentDidMount() {
25 if ('scripts' in this.props) this.runScripts();
26 }
27
28 render() {
29 const { html: __html } = this.props;
30 return <div className="rdmd-html" dangerouslySetInnerHTML={{ __html }} />;
31 }
32}
33
34HTMLBlock.propTypes = {
35 html: PropTypes.string,
36 scripts: PropTypes.any,
37};
38
39module.exports = sanitize => {
40 sanitize.tagNames.push('html-block');
41 sanitize.attributes['html-block'] = ['html', 'scripts'];
42 return HTMLBlock;
43};
44
\No newline at end of file