How to handle click event of parent of iframe in javascript (ReactJS)

Viewed 1788

My goal is to build a component in React with an iframe and be able to handle the click event on that iframe. However, my onClick event doesn't fire, only when I click on the parent div that is outside the scope of the child iframe it contains. Is there any solution to help me with this? Thanks.

export default function App() {
  return (
    <div className="App">
      <div onClick={() => alert("Testing")}>
        <iframe
          src="https://google.com.vn"
          title="stackoverflow"
          style={{ width: "100%", height: "100%" }}
        />
      </div>
   </div>
 );
}

My sandbox: https://codesandbox.io/s/onclick-on-parent-of-iframe-jjigu?file=/src/App.js

1 Answers

As the other commenter suggested, for security reasons you cannot listen for events inside the iframe from another domain.

Depending on what you need to accomplish, you could attach focus and blur event listeners to the window and use that as a proxy for when someone focuses the iframe.

import * as React from "react";
import "./styles.css";

function handleBlur() {
  console.log("document blurred");
}

function handleFocus() {
  console.log("document focused");
}

export default function App() {
  React.useEffect(() => {
    window.addEventListener("focus", handleFocus);
    window.addEventListener("blur", handleBlur);
    return () => {
      window.removeEventListener("focus", handleFocus);
      window.removeEventListener("blur", handleBlur);
    };
  });
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <iframe
        src="https://example.com"
        title="stackoverflow"
        style={{ width: "100%", height: "100%" }}
      />
    </div>
  );
}

One could go further to check if the iframe is focused by checking the document.activeElement https://developer.mozilla.org/en-US/docs/Web/API/Document/activeElement

Related