【问题标题】:How to handle click event of parent of iframe in javascript (ReactJS)如何在javascript(ReactJS)中处理iframe父级的点击事件
【发布时间】:2021-07-26 18:13:53
【问题描述】:

我的目标是在 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>
 );
}

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

【问题讨论】:

  • 在问题中包含部分代码会很好。链接将来可能会失效。
  • 除非您还控制 iframe 的域,否则无法解决此问题。出于安全原因,如果 iframe 内容显示的是来自不同域的页面,则对 iframe 内容的访问基本上为零。

标签: javascript reactjs iframe


【解决方案1】:

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

根据您需要完成的任务,您可以将 focusblur 事件侦听器附加到窗口,并将其用作某人聚焦 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>
  );
}

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

【讨论】:

猜你喜欢
  • 2011-07-24
  • 1970-01-01
  • 2011-11-11
  • 2019-11-11
  • 1970-01-01
  • 2011-04-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-13
相关资源
最近更新 更多