2021-04-08 16:24:21 +00:00
|
|
|
// Copyright 2021 Signal Messenger, LLC
|
|
|
|
// SPDX-License-Identifier: AGPL-3.0-only
|
|
|
|
|
|
|
|
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;
|
|
|
|
}
|
|
|
|
|
|
|
|
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);
|
|
|
|
};
|
|
|
|
|
2021-04-08 16:24:21 +00:00
|
|
|
onlineEventTarget.addEventListener('online', listener);
|
2021-07-23 22:02:36 +00:00
|
|
|
|
|
|
|
if (timeout !== undefined) {
|
|
|
|
setTimeout(() => {
|
|
|
|
cleanup();
|
|
|
|
reject(new Error('waitForOnline: did not come online in time'));
|
|
|
|
}, timeout);
|
|
|
|
}
|
2021-04-08 16:24:21 +00:00
|
|
|
});
|
|
|
|
}
|