我的目标是在React中构建一个带有iframe的组件,并能够处理该iframe上的单击事件。然而,我的onClick
事件不触发,只有当我点击父div,它是它所包含的子iframe的范围之外。有什么办法可以帮我解决这个问题吗?谢谢。
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内部的事件。
根据您需要完成的任务,您可以将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>
);
}
可以通过检查document.activeElement
https://developer.mozilla.org/en-US/docs/Web/API/Document/activeElement