Detect Click into Iframe using JavaScript

前端 未结 21 2560
轻奢々
轻奢々 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:20

    As found there : Detect Click into Iframe using JavaScript

    => We can use iframeTracker-jquery :

    $('.carousel-inner .item').each(function(e) {
        var item = this;
        var iFrame = $(item).find('iframe');
        if (iFrame.length > 0) {
            iFrame.iframeTracker({
                blurCallback: function(){
                    // Do something when iFrame is clicked (like firing an XHR request)
                    onItemClick.bind(item)(); // calling regular click with right context
                    console.log('IFrameClick => OK');
                }
            });
            console.log('IFrameTrackingRegistred => OK');
        }
    })
    
    0 讨论(0)
  • 2020-11-22 03:20

    Based in the answer of Paul Draper, I created a solution that work continuously when you have Iframes that open other tab in the browser. When you return the page continue to be active to detect the click over the framework, this is a very common situation:

              focus();
            $(window).blur(() => {
               let frame = document.activeElement;
               if (document.activeElement.tagName == "IFRAME") {
                 // Do you action.. here  frame has the iframe clicked
                  let frameid = frame.getAttribute('id')
                  let frameurl = (frame.getAttribute('src'));
               }            
            });
    
            document.addEventListener("visibilitychange", function () {
                if (document.hidden) {
    
                } else {
                    focus();
                }
            });
    

    The Code is simple, the blur event detect the lost of focus when the iframe is clicked, and test if the active element is the iframe (if you have several iframe you can know who was selected) this situation is frequently when you have publicity frames.

    The second event trigger a focus method when you return to the page. it is used the visibility change event.

    0 讨论(0)
  • 2020-11-22 03:21

    Mohammed Radwan, Your solution is elegant. To detect iframe clicks in Firefox and IE, you can use a simple method with document.activeElement and a timer, however... I have searched all over the interwebs for a method to detect clicks on an iframe in Chrome and Safari. At the brink of giving up, I find your answer. Thank you, sir!

    Some tips: I have found your solution to be more reliable when calling the init() function directly, rather than through attachOnloadEvent(). Of course to do that, you must call init() only after the iframe html. So it would look something like:

    <script>
    var isOverIFrame = false;
    function processMouseOut() {
        isOverIFrame = false;
        top.focus();
    }
    function processMouseOver() { isOverIFrame = true; }
    function processIFrameClick() {
        if(isOverIFrame) {
        //was clicked
        }
    }
    
    function init() {
        var element = document.getElementsByTagName("iframe");
        for (var i=0; i<element.length; i++) {
            element[i].onmouseover = processMouseOver;
            element[i].onmouseout = processMouseOut;
        }
        if (typeof window.attachEvent != 'undefined') {
            top.attachEvent('onblur', processIFrameClick);
        }
        else if (typeof window.addEventListener != 'undefined') {
            top.addEventListener('blur', processIFrameClick, false);
        }
    }
    </script>
    
    <iframe src="http://google.com"></iframe>
    
    <script>init();</script>
    
    0 讨论(0)
  • 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:

    <div class='banner' bannerid='yyy'>
        <iframe src='http://somedomain.com/whatever.html'></iframe>
    <div>
    

    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!

    0 讨论(0)
  • 2020-11-22 03:23

    I believe you can do something like:

    $('iframe').contents().click(function(){function to record click here });
    

    using jQuery to accomplish this.

    0 讨论(0)
  • 2020-11-22 03:26

    Assumptions -

    1. Your script runs outside the iframe BUT NOT in the outermost window.top window. (For outermost window, other blur solutions are good enough)
    2. A new page is opened replacing the current page / a new page in a new tab and control is switched to new tab.

    This works for both sourceful and sourceless iframes

    var ifr = document.getElementById("my-iframe");
    var isMouseIn;
    ifr.addEventListener('mouseenter', () => {
        isMouseIn = true;
    });
    ifr.addEventListener('mouseleave', () => {
        isMouseIn = false;
    });
    window.document.addEventListener("visibilitychange", () => {
        if (isMouseIn && document.hidden) {
            console.log("Click Recorded By Visibility Change");
        }
    });
    window.addEventListener("beforeunload", (event) => {
        if (isMouseIn) {
            console.log("Click Recorded By Before Unload");
        }
    });
    

    If a new tab is opened / same page unloads and the mouse pointer is within the Iframe, a click is considered

    0 讨论(0)
提交回复
热议问题