侦听 iframe 事件 - 打开一个 url

Listen for iframe event - on open a url

本文关键字:一个 url iframe 事件 侦听      更新时间:2023-09-26

我的移动网站中嵌入了一个iframe,其中iframe的内容包含一个带有标签的图像。我想侦听用户单击iframe中的图像并重定向到新页面的事件。

例如:

<!-- This is the content of the iframe -->
<!-- The hosting location is http://www.example.com/iframe.html -->
<a href="http://www.google.com" target="_blank">
<img src="http://www.example.com/image01.jpg">
</a>

然后

<!-- This is the content of the mobile site -->
<html>
<meta name="viewport" content="user-scalable=no, width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"/>
<iframe src="http://www.example.com/iframe.html"></iframe>
</html>

所以当用户点击 iframe 中的图片时,他会被重定向到 http://www.example.com,我想监听这个事件,我可以动态运行一些 javascript 函数。

有什么建议吗?谢谢。

2014年12月9日备注:

必须注意的一件事是,移动网站的内容会动态地传递到具有不同域的多个移动网站中。所以 window.parent 不起作用,因为 iframe 内容文件和 html 文件不在同一域中。

我还检查了方法postMessage(data,targetDomain(。但是,它只能在 iframe 内容文件和 html 文件的域已知的情况下工作。(就我而言,HTML文件的域是未知的,因为它是在具有不同域的多个移动站点上动态交付的(。

任何解决方案??

您可以使用window.parent .

在 iframe 页面中:

$('a').on("click", function(e) {
  window.parent.doStuff();
});

在您的主页中:

function doStuff(){ ... }