get iframe elements in react using ref
Asked Answered
C

2

7

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

Coincide answered 22/6, 2020 at 19:11 Comment(3)
Are there errors in the console? You might don't have a permission to access the iframe's DOM.Sensualist
I got this one : react-dom.development.js:328 Uncaught DOMException: Blocked a frame with origin "file://" from accessing a cross-origin frame.Coincide
That's what I thought. You don't have permission to access the DOM of an iframe in a different domain unless you own the iframe's website too.Sensualist
E
2

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

Exsert answered 11/8, 2021 at 12:25 Comment(0)
K
1

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);
Kaylee answered 10/9, 2022 at 5:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.