-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcustomCookie.html
More file actions
82 lines (68 loc) · 2.33 KB
/
customCookie.html
File metadata and controls
82 lines (68 loc) · 2.33 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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Custom Cookie</title>
<script>
// Normal Cookie provided by the browser
document.cookie = "name=Raghav";
// Cookie with an expiration time (in seconds))
document.cookie = "blog=TechCompositions;max-age=1";
console.log("Document Cookie", document.cookie);
setTimeout(() => {
console.log("Document Cookie", document.cookie);
}, 1500);
// Function to create the custom Cookie
const useCustomCookie = () => {
const store = new Map();
Object.defineProperty(document, "myCookie", {
configurable: true,
set: (val) => {
const { key, value, options } = parseCookieString(val);
let expiry = Infinity;
if (options["max-age"]) {
expiry = Date.now() + Number(options["max-age"]) * 1000;
}
store.set(key, { value, expiry });
},
get: () => {
const time = Date.now();
const cookies = [];
for (const [key, { value, expiry }] of store) {
if (expiry <= time) {
store.delete(key);
} else cookies.push(`${key}=${value}`);
}
return cookies.join("; ");
},
});
const parseCookieString = (str) => {
const [nameValue, ...rest] = str.split(";");
const [key, value] = separateKeyVal(nameValue);
const options = {};
for (let option of rest) {
const [key, value] = separateKeyVal(option);
options[key] = value;
}
return { key, value, options };
};
const separateKeyVal = (pair) => {
return pair.split("=").map((s) => s.trim());
};
};
useCustomCookie();
// Custom Cookie we created
document.myCookie = "name=Shubham";
// Custom Cookie with an expiration time (in seconds))
document.myCookie = "youtube=GreyLED;max-age=1";
console.log("Custom Cookie", document.myCookie);
setTimeout(() => {
console.log("Custom Cookie", document.myCookie);
}, 1500);
</script>
</head>
<body>
<h1>Custom Cookie</h1>
</body>
</html>