Skip to content

Instantly share code, notes, and snippets.

@Alex1990
Last active December 20, 2019 09:54
Show Gist options
  • Save Alex1990/046a6553dc83e22dd6f4 to your computer and use it in GitHub Desktop.
Save Alex1990/046a6553dc83e22dd6f4 to your computer and use it in GitHub Desktop.
Get the current active element safely.
/**
* 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;
}
@miherlosev
Copy link

Hello.
Can you call to mind scenario for

// IE11 returns a seemingly empty object in some cases when accessing
// document.activeElement from an <iframe>

@TheSharpieOne
Copy link

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment