getVisibilityWatcher.js 1.8 KB

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