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);
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.
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.
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.
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.
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);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With