/
browser.ts
120 lines (94 loc) · 2.31 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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
import {UAParser} from 'ua-parser-js';
const MOBILE_DEVICE_TYPES = ['mobile', 'tablet'];
export interface Options {
userAgent: string;
supported?: boolean;
bypass?: boolean;
}
export class Browser {
userAgent: string;
supported: boolean;
private ua: UAParser;
get name() {
return this.ua.getBrowser().name || '';
}
get version() {
return this.ua.getBrowser().version || '';
}
get majorVersion() {
const {version} = this;
if (version === '') {
return undefined;
}
const majorVersion = parseInt(version.split('.')[0], 10);
return Number.isNaN(majorVersion) ? undefined : majorVersion;
}
get unknown() {
return this.name === '';
}
get isMobile() {
return MOBILE_DEVICE_TYPES.includes(this.ua.getDevice().type);
}
get isDesktop() {
return !this.isMobile;
}
get isNativeApp() {
return this.ua.getUA().includes('Shopify Mobile/', 0);
}
get os() {
return this.ua.getOS().name || '';
}
get isWindows() {
return this.os.includes('Windows');
}
get isMac() {
return this.os.includes('Mac OS');
}
get isSafari() {
return this.name.includes('Safari');
}
get isChrome() {
return this.name.includes('Chrome');
}
get isAndroidChrome() {
return this.ua.getUA().includes('Android') && this.name.includes('Chrome');
}
get isAndroid() {
const os = this.ua.getOS();
return os.name && os.name.includes('Android');
}
get isFirefox() {
return this.name === 'Firefox';
}
get isIE() {
return this.name.includes('IE');
}
get isEdge() {
return this.name === 'Edge';
}
get isIOS() {
const os = this.ua.getOS();
const isStandardiOS = os.name && os.name.includes('iOS');
const isShopifyiOS =
/Shopify Mobile|Shopify POS|Shopify Ping/.test(this.userAgent) &&
this.userAgent.includes('iOS');
return isStandardiOS || isShopifyiOS;
}
constructor({userAgent, supported = true}: Options) {
this.userAgent = userAgent;
this.supported = supported;
this.ua = new UAParser(userAgent);
}
}
export function asPlainObject(browser?: Browser) {
if (browser == null) {
return {};
}
return {
name: browser.name,
version: browser.version,
isMobile: browser.isMobile,
isNativeApp: browser.isNativeApp,
isDesktop: browser.isDesktop,
};
}