【问题标题】:Listen for iframe event - on open a url监听 iframe 事件 - 打开一个 url
【发布时间】:2014-12-09 23:56:07
【问题描述】:

我的移动网站中嵌入了一个 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 文件的域是未知的,因为它是在具有不同域的多个移动站点上动态传递的)。

有什么解决办法吗??

【问题讨论】:

    标签: javascript jquery html iframe listener


    【解决方案1】:

    您可以使用window.parent

    在您的 iframe 页面中:

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

    在您的主页中:

    function doStuff(){ ... }
    

    【讨论】:

    • 如果 iframe 内容文件和 html 文件托管在同一个域中,这是一个很好的解决方案。但是,在我的情况下,html 文件被传送到具有不同域的不同移动站点。所以 window.parent 不能工作.......
    猜你喜欢
    • 1970-01-01
    • 2011-07-03
    • 1970-01-01
    • 1970-01-01
    • 2010-10-23
    • 2011-11-12
    • 2016-06-22
    • 2011-09-28
    • 1970-01-01
    相关资源
    最近更新 更多