2

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!

bushpop
  • 33
  • 2
  • "clicked" is printed multiple times in my console – kiranvj Aug 26 '15 at 21:51
  • 1
    This seems to work as you intend. Are you sure you're clicking outside of the ```iframe``` in between clicks? In order for the ```blur``` handler to fire, you're going to need to first restore focus to the parent document. – benjarwar Aug 26 '15 at 21:53
  • possible duplicate of [Add click event to iframe](http://stackoverflow.com/questions/15080222/add-click-event-to-iframe) – benjarwar Aug 26 '15 at 22:00

1 Answers1

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.

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

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

In the iframe you add:

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

In the parent you add:

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!"); }
});
Emil Borconi
  • 3,326
  • 2
  • 24
  • 40
  • I don't have acces in iframe. Iframe contain for example: bing.com, example.com, ... . – bushpop Aug 27 '15 at 06:59
  • Unfortunately, there is no way to interact with an iframe if it is not on the same domain, or you do not have access to it's source. – Emil Borconi Aug 27 '15 at 08:01