getActiveElement.js 915 B

12345678910111213141516171819202122232425262728293031323334353637383940
  1. "use strict";
  2. /**
  3. * Copyright (c) 2013-present, Facebook, Inc.
  4. *
  5. * This source code is licensed under the MIT license found in the
  6. * LICENSE file in the root directory of this source tree.
  7. *
  8. * @typechecks
  9. */
  10. /* eslint-disable fb-www/typeof-undefined */
  11. /**
  12. * Same as document.activeElement but wraps in a try-catch block. In IE it is
  13. * not safe to call document.activeElement if there is nothing focused.
  14. *
  15. * The activeElement will be null only if the document or document body is not
  16. * yet defined.
  17. *
  18. * @param {?DOMDocument} doc Defaults to current document.
  19. * @return {?DOMElement}
  20. */
  21. function getActiveElement(doc)
  22. /*?DOMElement*/
  23. {
  24. doc = doc || (typeof document !== 'undefined' ? document : undefined);
  25. if (typeof doc === 'undefined') {
  26. return null;
  27. }
  28. try {
  29. return doc.activeElement || doc.body;
  30. } catch (e) {
  31. return doc.body;
  32. }
  33. }
  34. module.exports = getActiveElement;