Dia 42/2019 - Gerenciando cookies do navegador

Desafio #92daysofcode que fiz no final de 2019. Nesse artigo temos o dia 42, mostrando o gerencimanento de cookies no navegador.

Pré-visualização

Código

Começamos com a estrutura do HTML.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<!DOCTYPE html>
<html lang="pt-br">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Day 42</title>
<style>
*, *:before, *:after { -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing:border-box; }
html { -webkit-box-sizing:border-box; -moz-box-sizing:border-box; box-sizing:border-box; font-size: 62.5%; }
* { margin: 0; padding: 0; list-style: none; outline: none; }
body { background: #000; color: #fff; font-family: Arial, Helvetica, sans-serif; }
.container { margin: 20px auto; max-width: 992px; width: 100%; }
</style>
<link rel="stylesheet" type="text/css" href="./day-42.css">
</head>
<body>
<div class="container">
<!-- form -->
</div>
<script src="./day-42.js"></script>
</body>
</html>
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
<div class="theme">
<ul class="theme-list">
<li class="theme-item"><button data-js="button" data-color="red" class="theme-button red"></button></li>
<li class="theme-item"><button data-js="button" data-color="blue" class="theme-button blue"></button></li>
<li class="theme-item"><button data-js="button" data-color="green" class="theme-button green"></button></li>
<li class="theme-item"><button data-js="button" data-color="yellow" class="theme-button yellow"></button></li>
</ul>
</div>

<form class="form">
<p class="form-group">
<label class="form-label">Name</label>
<input class="form-field" data-js="inpName" type="text">
</p>
<p class="form-group">
<label class="form-label">E-mail</label>
<input class="form-field" data-js="inpEmail" type="text" value="email@email.com">
</p>
<p class="form-group">
<label class="form-label">Password</label>
<div class="form-wrap">
<input class="form-field" data-js="inpPassword" type="password" value="day42">
<button class="form-button" type="button" data-js="changeInputType">show</button>
</div>
<p><button class="form-submit">save</button></p>
</form>

<h3 class="title">Cookies</h3>
<div class="cookies" data-js="cookies"></div>
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
.theme,
.form { margin: 30px auto; width: 300px; }

.theme-list { display: flex; flex-direction: row; }
.theme-item { margin: 0 10px; }
.theme-button { border: 4px dotted rgba(0, 0, 0, 0.4); border-radius: 50%; box-shadow: 0 2px 2px rgba(0, 0, 0, 0.2); cursor: pointer; height: 50px; width: 50px; }

.title { font-size: 1.4rem; margin: 30px 0 0; text-align: center; }

.form-group { margin-bottom: 10px; }
.form-wrap { display: flex; flex-direction: row; justify-content: space-between; }
.form-label { color: #333; display: block; font-size: 1.4rem; line-height: 1; margin-bottom: 5px; }
.form-field { border: 2px dotted rgba(0, 0, 0, 0.1); border-radius: 4px; box-shadow: 0 2px 2px rgba(0, 0, 0, 0.2); height: 35px; font-size: 1.2rem; padding: 0 10px; width: 100%; }

.form-wrap .form-field { border-radius: 4px 0 0 4px; }
.form-button { border: none; border-radius: 0 4px 4px 0; box-shadow: 0 2px 2px rgba(0, 0, 0, 0.2); cursor: pointer; height: 35px; width: 70px; }

.form-submit { background: rgba(0, 0, 0, 0.4); border: none; border-radius: 4px; box-shadow: 0 2px 2px rgba(0, 0, 0, 0.2); color: #fff; cursor: pointer; font-size: 1.2rem; height: 35px; margin-top: 30px; text-transform: uppercase; width: 100%; }

.cookies { border: 4px dotted rgba(0, 0, 0, 0.4); border-radius: 4px; font-size: 1.8rem; margin: 10px auto; padding: 10px; text-align: center; width: 400px; }

.red { background: #c51818; color: #640707; }
.blue { background: #3f57c5; color: #0d1d63; }
.green { background: #239c23; color: #054105; }
.yellow { background: #ddcb29; color: #4e4705; }
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
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
const xCookies = {
get: name => {
if (document.cookie.length === 0) {
return null;
}

let begin = document.cookie.indexOf(`${name}=`);

if (begin === -1) {
return null;
}

begin = begin + name.length + 1;

let end = document.cookie.indexOf(';', begin);

if (end == -1) {
end = document.cookie.length;
}

return decodeURIComponent( document.cookie.substring(begin, end) );
},
set: (name, value, days, hours) => {
if (days > 0 || hours > 0) {
const hs = hours > 0 ? hours : 24;
const h = 1000*60*60;
const milliseconds = days > 0 ? h*hs*days : h*hs;
const time = new Date().getTime() + milliseconds;
const date = new Date(time).toUTCString();
document.cookie = name + `=${encodeURIComponent(value)}; expires=${date}; path=/`;
} else {
document.cookie = name + `=${encodeURIComponent(value)}; path=/`
}
},
remove: name => {
if (name) {
document.cookie = name + `=''; expires=${new Date(1).toUTCString()}`;
}
},
getAll: () => {
if (document.cookie.length === 0) {
return null;
}

const cookies = {};
document.cookie.split(';').forEach(pairs => {
const pair = pairs.split('=');
cookies[ (pair[0]+'').trim() ] = decodeURIComponent(pair[1]);
})

return cookies;
},
check: name => {
name = xCookies.get(name);
return (name && name !== '') ? true : false;
}
}
// examples
// console.log(xCookies.set('test', 'test', 5));
// console.log(xCookies.set('test2', 'test2', 0, 5));
// console.log(xCookies.getAll());
// console.log(xCookies.get('test'));
// console.log(xCookies.check('test'));
// console.log(xCookies.remove('test2'));

// app
const body = document.querySelector('body');
const buttons = document.querySelectorAll('[data-js="button"]');

const inpName = document.querySelector('[data-js="inpName"]');
const inpPassword = document.querySelector('[data-js="inpPassword"]');
const changeInputType = document.querySelector('[data-js="changeInputType"]');

const cookies = document.querySelector('[data-js="cookies"]');

// show/hide
changeInputType.addEventListener('click', evt => {
if (inpPassword.getAttribute('type') === 'password') {
inpPassword.setAttribute('type', 'text');
changeInputType.innerHTML = 'hide';
} else {
inpPassword.setAttribute('type', 'password');
changeInputType.innerHTML = 'show';
}
});

// theme colors
buttons.forEach(button => {
button.addEventListener('click', evt => {
const color = evt.target.getAttribute('data-color');
body.className = '';
body.classList.add(color);
xCookies.set('theme', color, 1);
});
});

if (!xCookies.check('name')) {
setTimeout(() => {
const prName = prompt("Informe o seu nome?");

if (prName && prName !== '') {
xCookies.set('name', prName, 0, 5);
inpName.value = prName;
}
}, 1000);
}

if (xCookies.check('theme')) {
body.classList.add(xCookies.get('theme'));
}

if (xCookies.check('name')) {
inpName.value = xCookies.get('name');
}

cookies.innerHTML = JSON.stringify(xCookies.getAll());

// Check for refresh keys
// const f5key = 116; // f5
// const rkey = 82; // r
// const modkey = [17, 224, 91, 93]; // ctrl, left or right ⌘ key (firefox), Windows Key / Left ⌘ / Chromebook Search key, Windows Menu / Right ⌘

// let isRefresh = false;
// let modifierPressed = false;

// document.addEventListener('keydown', evt => {
// if (evt.which == f5key || modifierPressed && evt.which == rkey) {
// isRefresh = true;
// }

// if (modkey.indexOf(evt.which) >= 0) {
// modifierPressed = true;
// }
// });

// document.addEventListener('keyup', evt => {
// if (evt.which == f5key || evt.which == rkey) {
// isRefresh = false;
// }

// if (modkey.indexOf(evt.which) >= 0) {
// modifierPressed = false;
// }
// });

// unload
// window.onbeforeunload = () => {
// if (!isRefresh) {
// xCookies.remove('name');
// console.log('cookie removed');
// }
// }

Conclusão

A postagem original pode ser vista no meu Instagram e o código está acessível no meu Github.

Relacionados

Ao fechar este aviso ou continuar navegando no site Nerd Calistênico, você aceita o uso de cookies.

Este site usa cookies para assegurar a melhor experiência para os nossos usuários. Consulte nossa política de privacidade.

Uma nova versão está disponível. Clique aqui para atualizar.