如何在javascript(ReactJS)中处理iframe父级的点击事件

Pha*_*Tan 5 javascript iframe reactjs

我的目标是在 React 中使用 iframe 构建一个组件,并能够处理该 iframe 上的单击事件。但是,onClick只有当我单击位于其包含的子 iframe 范围之外的父 div 时,我的事件才不会触发。有什么解决方案可以帮助我解决这个问题吗?谢谢。

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>
 );
}
Run Code Online (Sandbox Code Playgroud)

我的沙箱: https://codesandbox.io/s/onclick-on-parent-of-iframe-jjigu ?file=/src/App.js

Foz*_*zle 2

正如另一位评论者所建议的,出于安全原因,您无法侦听来自另一个域的 iframe 内的事件。

根据您需要完成的任务,您可以将事件侦听器附加focus到blur窗口,并在有人聚焦 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>
  );
}
Run Code Online (Sandbox Code Playgroud)

人们可以通过检查https://developer.mozilla.org/en-US/docs/Web/API/Document/activeElement进一步检查 iframe 是否获得焦点document.activeElement