I have a component contains iframe and I want to access its content in react, I used ref to handle the iframe, how can I get all anchors tags from the iframe
here is my code :
const GridGenerator = () => {
const [loading, setLoading] = useState(true);
const gridIframe = useRef(null);
function handleIframe() {
setLoading(false);
const iframeItem = gridIframe.current;
const anchors = iframeItem.contentWindow.getElementsByTagName("a");
}
return (
<div>
{loading ? <div className={styles.loader} /> : null}
<iframe
title="Grid Generator"
ref={gridIframe}
src="https://collectearth.users.earthengine.app/view/collect-earth-grid-generator"
width="100%"
height="1000px"
frameBorder={0}
onLoad={handleIframe}
/>
<Link to={routes.HOME}>Go Back</Link>
</div>
);
};
so, it works well until :
const iframeItem = gridIframe.current;
and it returns iframe tag, but this line does not work well
const anchors = iframeItem.contentWindow.getElementsByTagName("a");
any solution ? Thank you
You need to access the document of contentWindow in order to get the elements, Window interface does not have any method called getElementsByTagName.
So, instead of
const anchors = iframeItem.contentWindow.getElementsByTagName("a");
you should do
const anchors = iframeItem.contentWindow.document.getElementsByTagName("a");
For me adding to Window worked, instead of Document:
Without bind():
function handleSubmit(e) {
alert('yay 1!', e);
}
iframeRef.current?.contentWindow?.addEventListener('click', handleSubmit, false);
With bind():
function handleSubmit2() {
alert('yay 2!', this.ele);
}
iframeRef.current?.contentWindow?.addEventListener('click', handleSubmit2.bind({ ele: iframeRef }), false);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With