forked from clerk/javascript
-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbrowser.ts
87 lines (80 loc) · 2.21 KB
/
browser.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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
/**
* Checks if the window object is defined. You can also use this to check if something is happening on the client side.
* @returns {boolean}
*/
export function inBrowser(): boolean {
return typeof window !== 'undefined';
}
const botAgents = [
'bot',
'spider',
'crawl',
'APIs-Google',
'AdsBot',
'Googlebot',
'mediapartners',
'Google Favicon',
'FeedFetcher',
'Google-Read-Aloud',
'DuplexWeb-Google',
'googleweblight',
'bing',
'yandex',
'baidu',
'duckduck',
'yahoo',
'ecosia',
'ia_archiver',
'facebook',
'instagram',
'pinterest',
'reddit',
'slack',
'twitter',
'whatsapp',
'youtube',
'semrush',
];
const botAgentRegex = new RegExp(botAgents.join('|'), 'i');
/**
* Checks if the user agent is a bot.
* @param userAgent - Any user agent string
* @returns {boolean}
*/
export function userAgentIsRobot(userAgent: string): boolean {
return !userAgent ? false : botAgentRegex.test(userAgent);
}
/**
* Checks if the current environment is a browser and the user agent is not a bot.
* @returns {boolean}
*/
export function isValidBrowser(): boolean {
const navigator = inBrowser() ? window?.navigator : null;
if (!navigator) {
return false;
}
return !userAgentIsRobot(navigator?.userAgent) && !navigator?.webdriver;
}
/**
* Checks if the current environment is a browser and if the navigator is online.
* @returns {boolean}
*/
export function isBrowserOnline(): boolean {
const navigator = inBrowser() ? window?.navigator : null;
if (!navigator) {
return false;
}
const isNavigatorOnline = navigator?.onLine;
// Being extra safe with the experimental `connection` property, as it is not defined in all browsers
// https://developer.mozilla.org/en-US/docs/Web/API/Navigator/connection#browser_compatibility
// @ts-ignore
const isExperimentalConnectionOnline = navigator?.connection?.rtt !== 0 && navigator?.connection?.downlink !== 0;
return isExperimentalConnectionOnline && isNavigatorOnline;
}
/**
* Runs `isBrowserOnline` and `isValidBrowser` to check if the current environment is a valid browser and if the navigator is online.
* @returns {boolean}
*/
export function isValidBrowserOnline(): boolean {
return isBrowserOnline() && isValidBrowser();
}