Last active
December 20, 2019 09:54
-
-
Save Alex1990/046a6553dc83e22dd6f4 to your computer and use it in GitHub Desktop.
Get the current active element safely.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Get the current active element safely. | |
* Ref: https://github.com/jquery/jquery-ui/blob/2b84531ae9331f60e4d739fabca6d78abde89ae1/ui/safe-active-element.js | |
*/ | |
function safeActiveElement(doc) { | |
doc = doc || document; | |
var activeElement; | |
// Support: IE 9 only | |
// IE9 throws an "Unspecified error" accessing document.activeElement from an <iframe> | |
// Support: IE 9 - 11 only | |
// IE may return null instead of an element | |
// Interestingly, this only seems to occur when NOT in an iframe | |
// Support: IE 11 only | |
// IE11 returns a seemingly empty object in some cases when accessing | |
// document.activeElement from an <iframe> | |
try { | |
activeElement = doc.activeElement; | |
if (!activeElement || !activeElement.nodeName) { | |
activeElement = doc.body; | |
} | |
} catch ( error ) { | |
activeElement = doc.body; | |
} | |
return activeElement; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks for this, note that IE 11 apparently also throws an "Unspecified error" accessing
document.activeElement
from an<iframe>
... That is what led me to this.