getActiveElement.js 912 B

123456789101112131415161718192021222324252627282930313233343536
  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) /*?DOMElement*/{
  22. doc = doc || (typeof document !== 'undefined' ? document : undefined);
  23. if (typeof doc === 'undefined') {
  24. return null;
  25. }
  26. try {
  27. return doc.activeElement || doc.body;
  28. } catch (e) {
  29. return doc.body;
  30. }
  31. }
  32. module.exports = getActiveElement;