generated from denorg/starter
-
Notifications
You must be signed in to change notification settings - Fork 1
/
mod.ts
51 lines (48 loc) · 1.21 KB
/
mod.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
export interface OnlineParams {
timeout?: number;
}
/**
* Timeout a Promise after a duration
* @param ms - Number of miliseconds
* @param promise - Promise to return
* @source https://github.com/github/fetch/issues/175#issuecomment-216791333
*/
function timeoutPromise(
ms: number,
promise: Promise<boolean>,
): Promise<boolean> {
return new Promise((resolve, reject) => {
const timeoutId = setTimeout(() => {
resolve(false);
}, ms);
promise.then(
(res) => {
clearTimeout(timeoutId);
resolve(res);
},
(err) => {
clearTimeout(timeoutId);
resolve(false);
},
);
});
}
async function checkOnline(
params?: OnlineParams,
): Promise<boolean> {
const text =
await (await (await fetch("http://captive.apple.com/hotspot-detect.html", {
headers: {
"User-Agent": "CaptiveNetworkSupport/1.0 wispr",
},
}))
.blob()).text();
return (text ?? "").toLowerCase().includes("success");
}
/** Check if you are online and connected to the internet */
export function isOnline(params?: OnlineParams) {
if (params?.timeout) {
return timeoutPromise(params.timeout, checkOnline(params));
}
return checkOnline(params);
}