Atur dan dapatkan cookie dalam javascript

Jika Anda tidak terbiasa dengan istilah tersebut, cookie adalah cara untuk menyimpan informasi tentang sesi browser Anda, dan menyimpan data tersebut selama periode waktu tertentu.

Sebelum cookie dibuat, situs web tidak tahu siapa Anda dari satu tampilan halaman ke tampilan berikutnya. Dibandingkan dengan pelacakan yang meluas saat ini, kedengarannya seperti mimpi yang menjadi kenyataan

Tetapi itu juga berarti bahwa situs web tidak memiliki cara untuk memasukkan Anda dan membuat Anda tetap masuk, atau mengingat preferensi dari satu halaman ke halaman berikutnya

Sementara teknologi seperti localStorage dan sessionStorage menyediakan cara yang jauh lebih baik untuk menyimpan data secara lokal, cookie masih memiliki tempatnya

Hari ini, kita akan melihat sekilas cara menyetel dan mendapatkan cookie di browser

Anda dapat menggunakan properti document.cookie_ untuk menyetel cookie

Nilainya berupa string, menggunakan format {KEY}={VALUE};. Cookie hanya dapat berisi nilai string

// Set a cookie named sandwich, with a value of turkey
document.cookie = 'sandwich=turkey;';

Cookie juga dapat menyertakan beberapa pengaturan opsional, sebagian besar menggunakan format

// expires in two weeks: 60 seconds x 60 minutes x 24 hours x 14 days
// we'll look at the math behind this in the next section
document.cookie = `snack=chips; path=/; max-age=${60 * 60 * 24 * 14};`;
0, dipisahkan dengan titik koma (
// expires in two weeks: 60 seconds x 60 minutes x 24 hours x 14 days
// we'll look at the math behind this in the next section
document.cookie = `snack=chips; path=/; max-age=${60 * 60 * 24 * 14};`;
1)

  • // expires in two weeks: 60 seconds x 60 minutes x 24 hours x 14 days
    // we'll look at the math behind this in the next section
    document.cookie = `snack=chips; path=/; max-age=${60 * 60 * 24 * 14};`;
    
    _2 - Jalur untuk menyetel cookie. Default ke jalur saat ini. Mungkin ide yang bagus untuk mengatur ini ke jalur root.
    // expires in two weeks: 60 seconds x 60 minutes x 24 hours x 14 days
    // we'll look at the math behind this in the next section
    document.cookie = `snack=chips; path=/; max-age=${60 * 60 * 24 * 14};`;
    
    _3
  • // expires in two weeks: 60 seconds x 60 minutes x 24 hours x 14 days
    // we'll look at the math behind this in the next section
    document.cookie = `snack=chips; path=/; max-age=${60 * 60 * 24 * 14};`;
    
    _4 - Domain untuk cookie. Default ke nama host saat ini
  • // expires in two weeks: 60 seconds x 60 minutes x 24 hours x 14 days
    // we'll look at the math behind this in the next section
    document.cookie = `snack=chips; path=/; max-age=${60 * 60 * 24 * 14};`;
    
    5 - Jumlah maksimum waktu untuk menyimpan cookie, dalam hitungan detik
  • // expires in two weeks: 60 seconds x 60 minutes x 24 hours x 14 days
    // we'll look at the math behind this in the next section
    document.cookie = `snack=chips; path=/; max-age=${60 * 60 * 24 * 14};`;
    
    6` - Tanggal untuk kedaluwarsa cookie
  • // expires in two weeks: 60 seconds x 60 minutes x 24 hours x 14 days
    // we'll look at the math behind this in the next section
    document.cookie = `snack=chips; path=/; max-age=${60 * 60 * 24 * 14};`;
    
    _7 - Cookie hanya dapat dikirimkan melalui HTTPS
  • // expires in two weeks: 60 seconds x 60 minutes x 24 hours x 14 days
    // we'll look at the math behind this in the next section
    document.cookie = `snack=chips; path=/; max-age=${60 * 60 * 24 * 14};`;
    
    8 - Apakah browser dapat mengirim cookie ke situs lain atau tidak. Standarnya,
    // expires in two weeks: 60 seconds x 60 minutes x 24 hours x 14 days
    // we'll look at the math behind this in the next section
    document.cookie = `snack=chips; path=/; max-age=${60 * 60 * 24 * 14};`;
    
    _9, hanya mengirim dengan permintaan situs yang sama dan navigasi
    // logs a single string with all of the cookies for a site
    console.log(document.cookie);
    
    0 permintaan;

// expires in two weeks: 60 seconds x 60 minutes x 24 hours x 14 days
// we'll look at the math behind this in the next section
document.cookie = `snack=chips; path=/; max-age=${60 * 60 * 24 * 14};`;
_

Jika Anda tidak menetapkan nilai

// logs a single string with all of the cookies for a site
console.log(document.cookie);
_3 atau
// logs a single string with all of the cookies for a site
console.log(document.cookie);
4, cookie berpotensi tetap berada di browser tanpa batas waktu. Sebagai praktik terbaik, biasanya Anda harus selalu menetapkan salah satu dari dua nilai tersebut

Semua cookie untuk sebuah situs disimpan sebagai string tunggal, yang membuat mendapatkan nilai salah satunya agak membosankan

// logs a single string with all of the cookies for a site
console.log(document.cookie);

Metode pembantu

// logs a single string with all of the cookies for a site
console.log(document.cookie);
_5 membuat ini lebih mudah

/**
 * Get the value of a cookie
 * Source: https://gist.github.com/wpsmith/6cf23551dd140fb72ae7
 * @param  {String} name  The name of the cookie
 * @return {String}       The cookie value
 */
function getCookie (name) {
	let value = `; ${document.cookie}`;
	let parts = value.split(`; ${name}=`);
	if (parts.length === 2) return parts.pop().split(';').shift();
}

Berikan nama cookie yang ingin Anda dapatkan nilainya

let sandwich = getCookie('sandwich');
let snack = getCookie('snack');

Untuk menghapus cookie, Anda perlu mengatur tanggal

// logs a single string with all of the cookies for a site
console.log(document.cookie);
3 menjadi
// logs a single string with all of the cookies for a site
console.log(document.cookie);
7, atau tanggal
// logs a single string with all of the cookies for a site
console.log(document.cookie);
4 ke waktu saat ini atau lebih cepat

Pastikan

// logs a single string with all of the cookies for a site
console.log(document.cookie);
_9 cocok dengan yang digunakan untuk menyetel cookie, atau tidak akan berfungsi

// Delete the cookie
document.cookie = `sandwich=turkey; path=/; max-age=0;`;

Browser menyediakan tingkat ruang penyimpanan yang berbeda untuk cookie, tetapi batas atas umumnya adalah 4093 byte (lebih dari 4kb)

Untuk browser dengan batas penyimpanan maksimum, jumlah ini adalah total untuk semua cookie di situs Anda. Oleh karena itu, Anda harus mencoba mengurangi jejak keseluruhan data Anda sebanyak mungkin

Buat Cookie dengan JavaScript . properti kue. Dengan JavaScript, cookie dapat dibuat seperti ini. dokumen. cookie = "username=John Doe"; Anda juga dapat menambahkan tanggal kedaluwarsa (dalam waktu UTC).
Panggil saja dokumen. cookie untuk mengambil nilai saat ini dari semua cookie. Anda kemudian dapat menyimpan nilai ini dalam variabel untuk manipulasi lebih lanjut
Pendekatan 1. .
Akses cookie menggunakan dokumen. Kue kering
Menggunakan. metode split() untuk membaginya menjadi “;”
Lintasi deretan cookie
Tambahkan semua cookie satu per satu dalam string untuk dicetak
Header respons HTTP Set-Cookie digunakan untuk mengirim cookie dari server ke agen pengguna, sehingga agen pengguna dapat mengirimkannya kembali ke server nanti. To send multiple cookies, multiple Set-Cookie headers should be sent in the same response.