Detect Click into Iframe using JavaScript

前端 未结 21 2570
轻奢々
轻奢々 2020-11-22 03:06

I understand that it is not possible to tell what the user is doing inside an iframe if it is cross domain. What I would like to do is track if the user clicke

21条回答
  •  执念已碎
    2020-11-22 03:22

    Based on Mohammed Radwan's answer I came up with the following jQuery solution. Basically what it does is keep track of what iFrame people are hovering. Then if the window blurs that most likely means the user clicked the iframe banner.

    the iframe should be put in a div with an id, to make sure you know which iframe the user clicked on:

    so:

    $(document).ready( function() {
        var overiFrame = -1;
        $('iframe').hover( function() {
            overiFrame = $(this).closest('.banner').attr('bannerid');
        }, function() {
            overiFrame = -1
        });
    

    ... this keeps overiFrame at -1 when no iFrames are hovered, or the 'bannerid' set in the wrapping div when an iframe is hovered. All you have to do is check if 'overiFrame' is set when the window blurs, like so: ...

        $(window).blur( function() {
            if( overiFrame != -1 )
                $.post('log.php', {id:overiFrame}); /* example, do your stats here */
        });
    });
    

    Very elegant solution with a minor downside: if a user presses ALT-F4 when hovering the mouse over an iFrame it will log it as a click. This only happened in FireFox though, IE, Chrome and Safari didn't register it.

    Thanks again Mohammed, very useful solution!

提交回复
热议问题