full fat get active element

by ian_smithz

HTML

<iframe id='one' src='/rcgw2wup/show/'></iframe>
<iframe id='two' src='/rcgw2wup/show/'></iframe>
<button id='button'>Get active element</button>

JavaScript

/**
* Return the active element in the main web or iframes
* @return HTMLElement
**/
function getActiveElement() {
    var focused = false;
    
    // Check if the active element is in the main web or no
    if( document.body === document.activeElement || document.activeElement instanceof HTMLIFrameElement ){
        // Search in iframes
        $('iframe').each(function(){
            var element = this.contentWindow.document.activeElement;
            // If there is a active element
            if( element !== this.contentWindow.document.body ){
                focused = element;
                return false; // Stop searching
            }
        });
    }
    else focused = document.activeElement;
    
    return focused; // Return element
}

$(document).ready(function(){
    setInterval(function(){
        var element = getActiveElement();
        if( element !== false ){
            console.log(element);
        }
    }, 1000);
});