Detect Click into Iframe using JavaScript

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

提交回复
热议问题