How can I get the parent coordinates when clicking an iframe inside it

17 views Asked by At

i want to get the coordinates of the parent containing a div when clicking inside the div. I already add an event listener in the iframe and I send the coordinates via postMessage but those are the coordinates of the iframe itself, I want the coordinates of the parent window, those are different. How can i achieve this?

I've already tried something like this:

useEffect(() => {
    const iframe = document.getElementById('titanpad') as HTMLIFrameElement;
    const iframeDocument = iframe?.contentDocument || iframe?.contentWindow?.document;

    const handleClick = (event: MouseEvent) => {
      const x = event.clientX;
      const y = event.clientY;
      setClickCoordinates({ x, y });
    };

    if (iframeDocument) {
      iframeDocument.addEventListener('click', handleClick);
    }

    return () => {
      if (iframeDocument) {
        iframeDocument.removeEventListener('click', handleClick);
      }
    };
  }, []);

This didn't work.

1

There are 1 answers

0
David Bradshaw On

You need to get the position of the iframe and add this to the position returned via postMessage.

const {x, y} = iframe.getBoundingClientRect()