Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get iframe elements in react using ref

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

like image 277
Maya Nour Avatar asked Jul 01 '26 16:07

Maya Nour


2 Answers

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");

like image 177
Arnau Avatar answered Jul 04 '26 04:07

Arnau


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);
like image 43
Manohar Reddy Poreddy Avatar answered Jul 04 '26 06:07

Manohar Reddy Poreddy