Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detecting when an iframe gets or loses focus

What's the correct way of detecting when an iframe gets or loses focus (i.e. will or will not receive keyboard events)? The following is not working in Fx4:

var iframe = /* my iframe */;
iframe.addEventListener("focus", function() { /* never gets called */ }, false);
like image 644
CAFxX Avatar asked Mar 28 '11 08:03

CAFxX


People also ask

Is it possible to use focus and blur events on iframes?

It is not possible to use the focus or blur events directly on an iframe but you can use them on the window to provide an event driven method of checking the document.activeElement. Thus you can accomplish what you're after. Although we're now in 2018, my code is being implemented in GTM and tries to be cross browser compatible back to IE 11.

Is it possible to avoid tracking if the iframe has focus?

I had to change the logic of my page to avoid the need of tracking if the iframe has focus. It is possible. See my answer. How to check when an iframe has been clicked in or out of as well as hover-state. Note: I would highly recommend you don't choose a polling method and go with an event driven method such as this.

Why should I use an iframe for my website?

But the thing with these editors is that you have to find a way to keep the focus and the selection when the user is clicking on all the buttons across the interface. Because an iframe offers an isolated environment, this means that the focus or the selection is never lost when you are clicking outside of it.

What event is triggered when the iframe is fully loaded?

It is triggered when the iframe is fully loaded. In other words, all static assets have been downloaded, and all the elements in the DOM tree have fired their load event. The error event that is triggered when the loading failed.


2 Answers

You can poll "document.activeElement" to determine if it matches the iframe. Polling isn't ideal, but it works:

function checkFocus() {
  if(document.activeElement == document.getElementsByTagName("iframe")[0]) {
    console.log('iframe has focus');
  } else {
    console.log('iframe not focused');
  }
}

window.setInterval(checkFocus, 1000); 
like image 170
Ryan Avatar answered Sep 21 '22 01:09

Ryan


i know it's old, but i also had the same problem.

i ended up using this little pice of code:

$(document).on('focusout', function(){
       setTimeout(function(){
       // using the 'setTimout' to let the event pass the run loop
       if (document.activeElement instanceof HTMLIFrameElement) {
             // Do your logic here..
        }
    },0);
});
like image 33
EliorCohen Avatar answered Sep 20 '22 01:09

EliorCohen