简体   繁体   English

捕获 iframe 上的点击事件

[英]capture click event on iframe

Im trying to do something like我试图做类似的事情

<div onClick={()=>{ console.log(captured)}}>
  <iframe />
</div>

Is not working.不管用。 Looks like iframe not allow to do that.看起来 iframe 不允许这样做。

Any suggestion?有什么建议吗?

It is completely normal;这是完全正常的; events bubble inside the dom tree, the iframe has it's own dom tree and thus wont bubble the event outside of it.事件在 dom 树内冒泡,iframe 有它自己的 dom 树,因此不会在它之外冒泡事件。

How does your setup look like?您的设置如何? If you control the content inside the iframe you could use the post message API to communicate between the iframe and parent, check:如果您控制 iframe 中的内容,您可以使用发布消息 API 在 iframe 和父级之间进行通信,检查:

https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage

If you do not control it then probably you could detect a blur event on the parent window, rather than the click event on the iframe.如果您不控制它,那么您可能会检测到父 window 上的模糊事件,而不是 iframe 上的点击事件。

Hope this helps希望这可以帮助

It isn't possible to read iframe content (DOM) from the parent page.无法从父页面读取 iframe 内容 (DOM)。

There is an jQuery plugin called IframeTracker .有一个名为IframeTracker的 jQuery 插件。 This should solve your problem.这应该可以解决您的问题。 You can check the GitHub page for more detailed information.您可以查看 GitHub 页面了解更多详细信息。

If you have access to the iframe and control it, you can create a js file and do something like this and put it in both the iframe and the parent window:如果您有权访问iframe并对其进行控制,则可以创建一个js文件并执行以下操作并将其放入iframe和父 window 中:

(function() {
  if (window.location != window.parent.location) {
    window.document.addEventListener('click', window.parent.iframe_clicked);
  }
})();

function iframe_clicked(event) {
  console.log("wow, no kiddin!");
}

Of course there are other ways like going trough setting up a server and ajax and doing this over network too which have their own usages.当然还有其他方法,例如通过设置服务器和ajax并通过网络进行此操作,它们也有自己的用途。

And also there's postMessage as well, which others have already mentioned so I'm gonna skip explaining it.还有postMessage ,其他人已经提到过,所以我将跳过解释它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM