forked from IronKinoko/userscripts
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcookie.ts
More file actions
66 lines (60 loc) · 1.44 KB
/
Copy pathcookie.ts
File metadata and controls
66 lines (60 loc) · 1.44 KB
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
type Options = {
name: string
value?: string
/** max age in seconds */
maxAge?: number
domain?: string
path?: string
sameSite?: 'strict' | 'lax' | 'none'
secure?: boolean
}
function set(name: string, value: string): void
function set(options: Options): void
function set(arg1: string | Options, arg2?: string) {
let options: Options = {
name: '',
value: '',
maxAge: 24 * 60 * 60,
path: '/',
}
if (typeof arg1 === 'object') {
Object.assign(options, arg1)
} else {
options.name = arg1
options.value = arg2!
}
options.value = encodeURIComponent(options.value!)
document.cookie = [
`${options.name}=${options.value}`,
`max-age=${options.maxAge}`,
!!options.domain && `domain=${options.domain}`,
!!options.path && `path=${options.path}`,
!!options.sameSite && `sameSite=${options.sameSite}`,
!!options.secure && `secure`,
]
.filter(Boolean)
.join(';')
}
function get(name: string): string | null {
let reg = new RegExp('(^| )' + name + '=([^;]*)(;|$)')
let arr = document.cookie.match(reg)
if (arr) {
return decodeURIComponent(arr[2])
} else {
return null
}
}
function remove(name: string): void
function remove(options: Options): void
function remove(arg1: string | Options): void {
if (typeof arg1 === 'string') {
set({ name: arg1, value: '', maxAge: 0 })
} else {
set({ ...arg1, maxAge: 0 })
}
}
export const Cookie = {
get,
set,
remove,
}