forked from ipfs/public-gateway-checker
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcheckViaImgSrc.ts
44 lines (40 loc) · 1.32 KB
/
checkViaImgSrc.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
// import { Log } from './Log'
// const log = new Log('checkViaImgSrc')
async function checkViaImgSrc (imgUrl: string | URL): Promise<void> {
// we check if gateway is up by loading 1x1 px image:
// this is more robust check than loading js, as it won't be blocked
// by privacy protections present in modern browsers or in extensions such as Privacy Badger
const imgCheckTimeout = 15000
return await new Promise((resolve, reject) => {
const img = new Image()
const timer: ReturnType<typeof setTimeout> = setTimeout(() => {
// clearTimeout(timer)
reject(new Error(`Timeout when attempting to load img from '${img.src}`))
}, imgCheckTimeout)
// const timeout = () => {
// if (timer == null) {
// return false
// }
// clearTimeout(timer)
// // timer = null
// return true
// }
const onImageError: OnErrorEventHandler = (event, source, lineno, colno, error) => {
clearTimeout(timer)
if (error == null) {
reject(new Error(`Unknown Error when attempting to load img from '${img.src}`))
} else {
reject(error)
}
}
img.onerror = onImageError
img.onload = () => {
// subdomain works
// timeout()
clearTimeout(timer)
resolve()
}
img.src = imgUrl.toString()
})
}
export { checkViaImgSrc }