Skip to content

Commit c93fbae

Browse files
committed
feat: Add head props.
1 parent 81f9710 commit c93fbae

File tree

2 files changed

+30
-5
lines changed

2 files changed

+30
-5
lines changed

src/index.tsx

Lines changed: 29 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,45 @@
1-
import React, { useMemo } from 'react';
1+
import React, { useMemo, useRef, useState } from 'react';
2+
import ReactDOM from 'react-dom';
23

34
export interface RunWebProps extends React.IframeHTMLAttributes<HTMLIFrameElement> {
45
css?: string;
56
js?: string;
67
html?: string;
78
title?: string;
9+
head?: React.ReactNode;
810
}
911

1012
export default React.forwardRef<HTMLIFrameElement, RunWebProps>((props, ref) => {
11-
const { html = '', css, js, title = 'Demo Title', ...other } = props;
12-
13+
const { html = '', css, js, title = 'Demo Title', head, onLoad, ...other } = props;
14+
const [isLoaded, setIsLoaded] = useState(false);
15+
const frameRef = useRef<HTMLIFrameElement>(null);
1316
const srcDoc = useMemo(() => {
17+
setIsLoaded(false);
1418
const jsString = js ? `<script type="text/javascript">${js}</script>` : '';
1519
const cssString = css ? `<style>${css}</style>` : '';
1620
return `<!DOCTYPE html><html><head>${cssString}</head><body>${html}</body>${jsString}</html>`;
1721
}, [css, html, js]);
1822

19-
return <iframe title={title} width="100%" height="100%" style={{ border: 0 }} {...other} ref={ref} srcDoc={srcDoc} />;
23+
function renderFrameContents() {
24+
if (!frameRef.current || !frameRef.current.contentDocument || !frameRef.current.contentWindow) return null;
25+
return [ReactDOM.createPortal(head, frameRef.current.contentDocument.head)];
26+
}
27+
28+
return (
29+
<iframe
30+
title={title}
31+
width="100%"
32+
height="100%"
33+
style={{ border: 0 }}
34+
{...other}
35+
onLoad={(evn) => {
36+
setIsLoaded(true);
37+
onLoad && onLoad(evn);
38+
}}
39+
ref={frameRef}
40+
srcDoc={srcDoc}
41+
>
42+
{isLoaded && renderFrameContents()}
43+
</iframe>
44+
);
2045
});

website/pages/run/index.tsx

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -95,7 +95,7 @@ export default function Run() {
9595
</div>
9696
</Split>
9797
<div style={{ minWidth: 120, flex: 1 }}>
98-
<RunWeb css={cssStr} js={jsStr} html={htmlStr} />
98+
<RunWeb css={cssStr} js={jsStr} html={htmlStr} head={<meta charSet="utf-8" />} />
9999
</div>
100100
</Split>
101101
</div>

0 commit comments

Comments
 (0)