Detect Click into Iframe using JavaScript

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

    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.

提交回复
热议问题