计算iframe的点击次数 [英] counting clicks on iframe

查看:95
本文介绍了计算iframe的点击次数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

jQuery(document).ready(function (e) {
    focus();
    var listener = addEventListener('blur', function() {
        if(document.activeElement === document.getElementById('my_iFrame')) {
            console.log("clicked!");
        }
        removeEventListener(listener);
    });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<iframe src="http://example.com" id="my_iFrame"></iframe>

此代码仅计数一次.如何计算更多点击?

谢谢!

This code count only one click. How to do counting more clicks?

Thanks!

推荐答案

@benjarwar在他的两条评论中都是正确的,但是我认为以下解决方案比另一篇文章中建议的解决方案更为优雅,但这篇文章是闲置超过1年的时间,我将在此处发布解决方案.

@benjarwar is right in both of his comments, however I consider the following solution more elegant than the one suggested in the other post, but being a post which is not active for over 1 year I will post the solution here.

只要您有权访问iframe和父框架代码,这将适用于跨域.

This will work cross domain as well as long as you have access to both the iframe and the parent frame code.

假设您将在父级和iframe中都使用jQuery!

Assumption made that you will use jQuery in both parent and iframe as well!

在iframe中添加:

In the iframe you add:

$("html").on("click",function(){
parent.postMessage("click", "*");
});

在父级中添加:

window.addEventListener("message", function(event) { 
 if (event.data=="click") 
 //above if only added to be sure you are not getting some other messages post to you parent page.
   { console.log("clicked!"); }
});

这篇关于计算iframe的点击次数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆