Dalam tutorial ini, kita akan mempelajari cara MENGATUR, MENDAPATKAN, dan MENGHAPUS Kuki menggunakan JavaScript Vanilla. Kita akan membuat metode untuk semua operasi agar dapat digunakan kembali. Ini akan membantu Anda dalam proyek JavaScript Anda.
Memulai
Ikuti langkah-langkah berikut untuk menggunakan kode dalam dokumen HTML Anda.
Daftar Isi Artikel
Dasar
Tambahkan kode JavaScript berikut di bawah <script> di bagian kepala dokumen HTML Anda.
/*!
* cookie.js by Fineshop Design
* ----------------------------
*
* MIT License
*
* Copyright (c) 2021 Fineshop Design
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
window.cookie =
window.cookie ||
Object.defineProperties(
{},
{
value: {
get() {
return document.cookie;
},
set(value) {
document.cookie = value;
},
},
get: {
value(key) {
const regex = new RegExp(
`(?:^|; )${encodeURIComponent(key).replace(
/[-\/\\^$*+?.()|[\]{}]/g,
"\\$&"
)}=([^;]*)`
);
const matches = this.value.match(regex);
if (matches && typeof matches[1] === "string") {
return decodeURIComponent(matches[1]);
}
return null;
},
},
getAll: {
value() {
const cookies = {};
const cookieArray = this.value.split("; ");
for (let i = 0; i < cookieArray.length; i++) {
const cookieParts = cookieArray[i].split("=");
if (typeof cookieParts[0] === "string") {
const cookieName = decodeURIComponent(cookieParts[0]);
const cookieValue = cookieParts[1]
? decodeURIComponent(cookieParts[1])
: "";
cookies[cookieName] = cookieValue;
}
}
return cookies;
},
},
has: {
value(key) {
return this.get(key) !== null;
},
},
set: {
value(key, value, options) {
const object = Object.assign({ path: "/" }, options);
let cookieString = `${encodeURIComponent(key)}=${
typeof value !== "undefined" ? encodeURIComponent(value) : ""
}`;
for (let flagKey in object) {
let flagValue = object[flagKey];
switch (flagKey) {
case "expires":
if (flagValue instanceof Date) {
flagValue = flagValue.toUTCString();
}
break;
case "maxAge":
flagKey = "max-age";
break;
case "sameSite":
case "samesite":
flagKey = "samesite";
if (flagValue === "none") {
flagValue = true;
}
break;
}
cookieString += `; ${flagKey}`;
const shouldAddValue =
typeof flagValue === "boolean"
? flagValue !== true
: typeof flagValue !== "undefined";
if (shouldAddValue) {
cookieString += `=${flagValue}`;
}
}
this.value = cookieString;
return cookieString;
},
},
remove: {
value(key) {
this.set(key, "", {
maxAge: -1,
});
},
},
clear: {
value() {
for (const key in this.getAll()) {
this.remove(key);
}
},
},
keys: {
get() {
return Object.keys(this.getAll());
},
},
size: {
get() {
return this.keys.length;
},
},
}
);
Fungsi
- cookie
- .get(key) ⇒
string | null - .getAll() ⇒
Record<string, string> - .has(key) ⇒
boolean - .set(key, value, [config]) ⇒
string - .remove(key) ⇒
void - .clear(key) ⇒
void
cookie.set(key, value, [config]) ⇒ string
Untuk mengatur cookie dengan kunci dan nilai yang diinginkan.
| Param | Type | Default | Description |
|---|---|---|---|
| key | string |
Key of the cookie to set | |
| value | string |
Value of the cookie key | |
| [config] | object |
{ path: "/" } |
To add "max-age" (number), secure (boolean), etc |
Pengembalian:
string
Contoh:
const userDetails = {
name: "Deo Kumar",
email: "deo@fineshopdesign.com"
};
cookie.set("user", JSON.stringify(userDetails), {
secure: true,
maxAge: 3600 // will expire after 1 hour
});
cookie.get(key) ⇒ string
Untuk mendapatkan cookie dengan kuncinya.
| Param | Type | Default | Description |
|---|---|---|---|
| key | string |
Key of the cookie to get |
Pengembalian:
string | null: Mengembalikan nilai kunci cookie jika ada, jika tidak null.
Contoh:
const cookieValue = cookie.get("user");
const userObj = cookieValue ? JSON.parse(cookieValue) : null;
console.log(userObj);
cookie.getAll() ⇒ Record<string, string>
Mengembalikan pasangan key-value dari cookie yang ada.
Pengembalian:
Record<string, string>
Contoh:
cookie.getAll(); // { user: '{"name":"Deo Kumar","email":"deo@fineshopdesign.com"}' }
cookie.remove(key) ⇒ void
Untuk menghapus cookie dengan kuncinya.
| Param | Type | Default | Description |
|---|---|---|---|
| key | string |
Key of the cookie to remove |
Pengembalian:
undefined
Contoh:
cookie.remove("user");
Ada lebih banyak metode yang tersedia, Anda dapat mencobanya sendiri 😁.
Postingan Terkait
Copyright (c):
fineshopdesign.com