简体   繁体   中英

Track clicks inside iframe with Jquery

I'm trying to figure out a way of tracking clicks inside an iframe with jquery. The iframe is locate on the same domain but still I don't seem to be able to make this work, here's my code:

<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.6.2.min.js"></script>
<script type="text/javascript">
    var clicks = 0;
    $('#myframe').load(function() {
        alert('loaded');
        var that = $(this);
        that.contents().find('a').bind('click', function(e) {
            e.preventDefault();
            clicks++;
            $('#clicks').html(clicks);
        });
    });
</script>
</head>
<body>
Clicks: <span id="clicks" >0</span>
<iframe id="myframe" src="test_iframe.php" width="500" height="500"></iframe>
</body>
</html>

Any idea of what could be wrong ?

I've saw other questions very similar to this one at SO but none of the answers solved my problem.

UPDATE:

I've updated my code at http://www.politicos.biz/stack/iframe_click.php with @Wes code, it works on jsfiddle but not on my site.

Make sure that the iframe is fully loaded befor you add the event.

I would expect the handler to be added with .document

$('body', window.parent.frames[0].document).click( 
    function(){} 
);

OR

$('body', $('templateframe')[0].document).click( 
    function(){} 
);

Here is an example:

http://jsfiddle.net/wesbos/VxA8t/1/

$(function() {
    var clicks = 0;
    $('#myframe').contents().find('a').bind('click', function(e) {
        e.preventDefault();
        clicks++;
        $('#clicks').html(clicks);
    });
});

You need to find the link first and then bind to it.

Your code should be something like this:

$('body', $('templateframe')).contents().find('a').click(function(event) {
  alert("Link Clicked");
});

on the parent frame, create a function to be called from inside the iframe.

parent:

var click = 0;
function addClick()
{
    click++;
}

then, call it from the iframe

parent.addClick();

finally, simple refer to click for the number of click count. Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM