In order to detect the loss of focus, for accessibility audits, I personally use the ugly combination of all the following:
(function($){
var focusCounter = 0;
/* Set focus outline (CSS, jQuery): */
$("*").on("focus","body",function(e){$(e.target).css("outline","5px solid orange");$(e.target).on("blur",function(e){$(e.target).css("outline","none");})});
/* Log keypress */
$(document).on('keydown',function(e){
console.log("========= KEYDOWN ", e.key, " ==================");
});
/* Log currently focused element (On start) */
console.log("CURRENT: ",document.activeElement);
/* Log focused element (On focus) */
document.addEventListener("focus",function(){
console.log(
"[ " + (focusCounter++).toString() + " ]",
"FOCUSED: ",
"<" + document.activeElement.nodeName + ">",
($.trim($(document.activeElement).text())? $.trim($(document.activeElement).text()) : $.trim($(document.activeElement).val())).replace(/(\r\n|\n|\r)/gm, "").substring(0, 30) + '...',
document.activeElement
);
},true);
/* Try to detect loss of focus (Works in Chrome) */
document.addEventListener("focusout", function(event){console.log((!event.relatedTarget)?"⚠ FOCUS LOST":"");});
/* Fallback, checks in intervals if the focus is still active/lost e.g. if onfocus or onfocusout didn't work */
(function(){setInterval(function(){console.log('interval check: ',(document.body===document.activeElement)?"FOCUS LOST":"ok");},8500);})();
})(jQuery);
Idea: All of those I set as a bookmarklet so I can easily access it