1 | /*
|
2 | * Copyright 2020 Google LLC
|
3 | *
|
4 | * Licensed under the Apache License, Version 2.0 (the "License");
|
5 | * you may not use this file except in compliance with the License.
|
6 | * You may obtain a copy of the License at
|
7 | *
|
8 | * https://www.apache.org/licenses/LICENSE-2.0
|
9 | *
|
10 | * Unless required by applicable law or agreed to in writing, software
|
11 | * distributed under the License is distributed on an "AS IS" BASIS,
|
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
13 | * See the License for the specific language governing permissions and
|
14 | * limitations under the License.
|
15 | */
|
16 |
|
17 | import {onBFCacheRestore} from './onBFCacheRestore.js';
|
18 | import {onHidden} from './onHidden.js';
|
19 |
|
20 | let firstHiddenTime = -1;
|
21 |
|
22 | const initHiddenTime = () => {
|
23 | return document.visibilityState === 'hidden' ? 0 : Infinity;
|
24 | }
|
25 |
|
26 | const trackChanges = () => {
|
27 | // Update the time if/when the document becomes hidden.
|
28 | onHidden(({timeStamp}) => {
|
29 | firstHiddenTime = timeStamp
|
30 | }, true);
|
31 | };
|
32 |
|
33 | export const getFirstHidden = () => {
|
34 | if (firstHiddenTime < 0) {
|
35 | // If the document is hidden when this code runs, assume it was hidden
|
36 | // since navigation start. This isn't a perfect heuristic, but it's the
|
37 | // best we can do until an API is available to support querying past
|
38 | // visibilityState.
|
39 | if (self.__WEB_VITALS_POLYFILL__) {
|
40 | firstHiddenTime = self.webVitals.firstHiddenTime;
|
41 | if (firstHiddenTime === Infinity) {
|
42 | trackChanges();
|
43 | }
|
44 | } else {
|
45 | firstHiddenTime = initHiddenTime();
|
46 | trackChanges();
|
47 | }
|
48 |
|
49 | // Reset the time on bfcache restores.
|
50 | onBFCacheRestore(() => {
|
51 | // Schedule a task in order to track the `visibilityState` once it's
|
52 | // had an opportunity to change to visible in all browsers.
|
53 | // https://bugs.chromium.org/p/chromium/issues/detail?id=1133363
|
54 | setTimeout(() => {
|
55 | firstHiddenTime = initHiddenTime();
|
56 | trackChanges();
|
57 | }, 0);
|
58 | });
|
59 | }
|
60 | return {
|
61 | get timeStamp() {
|
62 | return firstHiddenTime;
|
63 | }
|
64 | }
|
65 | };
|