generated from denorg/starter
-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
03da2fd
commit 67f98ed
Showing
1 changed file
with
46 additions
and
4 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,9 +1,51 @@ | ||
/** Check if you are online and connected to the internet */ | ||
export async function isOnline( | ||
{ timeout, family }: { timeout?: number; family?: number }, | ||
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")) | ||
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); | ||
} |