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 |
|
18 | export interface OnHiddenCallback {
|
19 | (event: Event): void;
|
20 | }
|
21 |
|
22 | let beforeUnloadFixAdded = false;
|
23 |
|
24 | export const onHidden = (cb: OnHiddenCallback, once?: boolean) => {
|
25 | // Adding a `beforeunload` listener is needed to fix this bug:
|
26 | // https://bugs.chromium.org/p/chromium/issues/detail?id=987409
|
27 | if (!beforeUnloadFixAdded &&
|
28 | // Avoid adding this in Firefox as it'll break bfcache:
|
29 | // https://stackoverflow.com/questions/9847580/how-to-detect-safari-chrome-ie-firefox-and-opera-browser
|
30 | // @ts-ignore
|
31 | typeof InstallTrigger === 'undefined') {
|
32 | // eslint-disable-next-line @typescript-eslint/no-empty-function
|
33 | addEventListener('beforeunload', () => {});
|
34 | beforeUnloadFixAdded = true;
|
35 | }
|
36 |
|
37 | const onVisibilityChange = (event: Event) => {
|
38 | if (document.visibilityState === 'hidden') {
|
39 | cb(event);
|
40 | if (once) {
|
41 | removeEventListener('visibilitychange', onVisibilityChange, true);
|
42 | }
|
43 | }
|
44 | }
|
45 | addEventListener('visibilitychange', onVisibilityChange, true);
|
46 | };
|