javascript - 监听 iframe 事件 - 打开 URL

标签 javascript jquery html iframe listener

我的移动网站中嵌入了一个 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(){ ... }

关于javascript - 监听 iframe 事件 - 打开 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27345426/

相关文章:

javascript - Google Analytics Embed API 中的多系列图表

javascript - 更改可观察值

jquery - 使用 jQuery 插入表格列

jquery - 如何在 css3 或 jquery 中将背景图像加载为滚动

html - jQuery:使 div fadeOut + .live() + .delay() 函数合并

html - 如何在没有下载的情况下在 ionic 应用程序中显示 pdf 文件

javascript - 使用 jQuery 进行字符串操作

javascript - 确认后才重定向

javascript - 如何对多个 DIV 使用 JQuery 切换?

javascript - 有什么方法可以让 div 在 ipad 中滚动吗?