I'm loading html into an iframe through srcDoc with the sandbox="allow-same-origin"
.
I notice that frameRef.contentDocument.body.innerHTML
is empty even though the content displays. I set an effect to watch that property and it is always undefined.
How can I reliably get the body of the iframe's content and be able to watch it for changes?
Code:
export default function App() {
const [frameElement, setFrameElement] = React.useState(null);
const [templateHtml, setTemplateHtml] = React.useState(null);
const handleFrameElement = React.useCallback(e => {
setFrameElement(e.target);
}, []);
React.useEffect(() => {
setTimeout(() => setTemplateHtml(html), 1200);
}, []);
React.useEffect(() => {
console.log(
"HOOK ",
frameElement?.contentDocument?.body?.innerHTML?.length
);
}, [frameElement]);
return (
<div>
{templateHtml && (
<iframe
srcDoc={templateHtml}
sandbox="allow-same-origin"
onl oad={handleFrameElement}
/>
)}
</div>
);
}