I'm using an iframe to display a fetched HTML document in React and would like to listen for clicks on DOM elements inside the iframe.
For example I would like to console.log the DOM element I've clicked inside the iframe
I've tried using useRef and onClick but it doesn't seem to be working on the iFrame
I'm using Next.js to fetch the website HTML before adding to the the iframe
export default function Home() {
const [html, setHtml] = useState()
const ref = useRef(null);
const getDownload = async () => {
const response = await fetch('http://localhost:3000/api/getWebsite')
const data = await response.json()
setHtml(data)
}
return (
<main>
<iframe srcDoc={html} ref={ref} ></iframe>
</main>
)
}
You can access the contentDocument
of the frame after it loads.
useEffect(() => {
const frame = ref.current;
function loadHandler() {
frame.contentDocument.addEventListener('click', e => {
console.log('clicked', e.target);
});
}
frame.addEventListener('load', loadHandler);
return () => frame.removeEventListener('load', loadHandler);
}, []);