2022-02-25 18:37:15 +00:00
|
|
|
// Copyright 2021-2022 Signal Messenger, LLC
|
2021-04-08 16:24:21 +00:00
|
|
|
// SPDX-License-Identifier: AGPL-3.0-only
|
|
|
|
|
2022-02-25 18:37:15 +00:00
|
|
|
import { clearTimeoutIfNecessary } from './clearTimeoutIfNecessary';
|
|
|
|
|
2021-04-08 16:24:21 +00:00
|
|
|
export function waitForOnline(
|
|
|
|
navigator: Readonly<{ onLine: boolean }>,
|
2021-07-23 22:02:36 +00:00
|
|
|
onlineEventTarget: EventTarget,
|
|
|
|
options: Readonly<{ timeout?: number }> = {}
|
2021-04-08 16:24:21 +00:00
|
|
|
): Promise<void> {
|
2021-07-23 22:02:36 +00:00
|
|
|
const { timeout } = options;
|
|
|
|
|
|
|
|
return new Promise((resolve, reject) => {
|
2021-04-08 16:24:21 +00:00
|
|
|
if (navigator.onLine) {
|
|
|
|
resolve();
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2021-11-01 18:38:26 +00:00
|
|
|
let timeoutId: undefined | ReturnType<typeof setTimeout>;
|
|
|
|
|
2021-04-08 16:24:21 +00:00
|
|
|
const listener = () => {
|
2021-07-23 22:02:36 +00:00
|
|
|
cleanup();
|
2021-04-08 16:24:21 +00:00
|
|
|
resolve();
|
|
|
|
};
|
|
|
|
|
2021-07-23 22:02:36 +00:00
|
|
|
const cleanup = () => {
|
|
|
|
onlineEventTarget.removeEventListener('online', listener);
|
2022-02-25 18:37:15 +00:00
|
|
|
clearTimeoutIfNecessary(timeoutId);
|
2021-07-23 22:02:36 +00:00
|
|
|
};
|
|
|
|
|
2021-04-08 16:24:21 +00:00
|
|
|
onlineEventTarget.addEventListener('online', listener);
|
2021-07-23 22:02:36 +00:00
|
|
|
|
|
|
|
if (timeout !== undefined) {
|
2021-11-01 18:38:26 +00:00
|
|
|
timeoutId = setTimeout(() => {
|
2021-07-23 22:02:36 +00:00
|
|
|
cleanup();
|
|
|
|
reject(new Error('waitForOnline: did not come online in time'));
|
|
|
|
}, timeout);
|
|
|
|
}
|
2021-04-08 16:24:21 +00:00
|
|
|
});
|
|
|
|
}
|