Detecting when an iframe gets or loses focus

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); 

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);
});