getVisibilityWatcher.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. import { WINDOW } from '../../types.js';
  2. import { onHidden } from './onHidden.js';
  3. /*
  4. * Copyright 2020 Google LLC
  5. *
  6. * Licensed under the Apache License, Version 2.0 (the "License");
  7. * you may not use this file except in compliance with the License.
  8. * You may obtain a copy of the License at
  9. *
  10. * https://www.apache.org/licenses/LICENSE-2.0
  11. *
  12. * Unless required by applicable law or agreed to in writing, software
  13. * distributed under the License is distributed on an "AS IS" BASIS,
  14. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15. * See the License for the specific language governing permissions and
  16. * limitations under the License.
  17. */
  18. let firstHiddenTime = -1;
  19. const initHiddenTime = () => {
  20. // If the document is hidden and not prerendering, assume it was always
  21. // hidden and the page was loaded in the background.
  22. return WINDOW.document.visibilityState === 'hidden' && !WINDOW.document.prerendering ? 0 : Infinity;
  23. };
  24. const trackChanges = () => {
  25. // Update the time if/when the document becomes hidden.
  26. onHidden(({ timeStamp }) => {
  27. firstHiddenTime = timeStamp;
  28. }, true);
  29. };
  30. const getVisibilityWatcher = (
  31. ) => {
  32. if (firstHiddenTime < 0) {
  33. // If the document is hidden when this code runs, assume it was hidden
  34. // since navigation start. This isn't a perfect heuristic, but it's the
  35. // best we can do until an API is available to support querying past
  36. // visibilityState.
  37. firstHiddenTime = initHiddenTime();
  38. trackChanges();
  39. }
  40. return {
  41. get firstHiddenTime() {
  42. return firstHiddenTime;
  43. },
  44. };
  45. };
  46. export { getVisibilityWatcher };
  47. //# sourceMappingURL=getVisibilityWatcher.js.map