1 |
|
2 |
|
3 | const React = require('react');
|
4 | const PropTypes = require('prop-types');
|
5 |
|
6 |
|
7 |
|
8 |
|
9 | const 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 |
|
18 | class 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 |
|
34 | HTMLBlock.propTypes = {
|
35 | html: PropTypes.string,
|
36 | scripts: PropTypes.any,
|
37 | };
|
38 |
|
39 | module.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 |