Javascript mengatur file lokal cookie

My 2 functions to use "live cookies":

    function SetCookieLive($name, $value='', $expire = 0, $path = '', $domain='', $secure=false, $httponly=false)
    {
        $_COOKIE[$name] = $value;
        return setcookie($name, $value, $expire, $path, $domain, $secure, $httponly);
    }

    function RemoveCookieLive($name)
    {
        unset($_COOKIE[$name]);
        return setcookie($name, NULL, -1);
    }
?>

Cookie adalah serangkaian kecil data yang disimpan langsung di browser. Mereka adalah bagian dari protokol HTTP, ditentukan oleh spesifikasi RFC 6265

Cookie biasanya disetel oleh server web menggunakan respons

document.cookie = "user=John"; // update only cookie named 'user'
alert(document.cookie); // show all cookies
2 HTTP-header. Kemudian, browser secara otomatis menambahkannya ke (hampir) setiap permintaan ke domain yang sama menggunakan
document.cookie = "user=John"; // update only cookie named 'user'
alert(document.cookie); // show all cookies
3 HTTP-header

Salah satu kasus penggunaan yang paling umum adalah otentikasi

  1. Saat masuk, server menggunakan
    document.cookie = "user=John"; // update only cookie named 'user'
    alert(document.cookie); // show all cookies
    _2 HTTP-header sebagai respons untuk menyetel cookie dengan "pengidentifikasi sesi" unik
  2. Lain kali ketika permintaan dikirim ke domain yang sama, browser mengirimkan cookie melalui internet menggunakan
    document.cookie = "user=John"; // update only cookie named 'user'
    alert(document.cookie); // show all cookies
    3 HTTP-header
  3. Jadi server tahu siapa yang membuat permintaan

Kami juga dapat mengakses cookie dari browser, menggunakan properti

document.cookie = "user=John"; // update only cookie named 'user'
alert(document.cookie); // show all cookies
6

Ada banyak hal rumit tentang cookie dan opsinya. Dalam bab ini kita akan membahasnya secara rinci

Apakah browser Anda menyimpan cookie dari situs ini?

// At javascript.info, we use Google Analytics for statistics,
// so there should be some cookies
alert( document.cookie ); // cookie1=value1; cookie2=value2;...

Nilai

document.cookie = "user=John"; // update only cookie named 'user'
alert(document.cookie); // show all cookies
6 terdiri dari
document.cookie = "user=John"; // update only cookie named 'user'
alert(document.cookie); // show all cookies
8 pasang, dibatasi oleh
document.cookie = "user=John"; // update only cookie named 'user'
alert(document.cookie); // show all cookies
9. Masing-masing adalah cookie yang terpisah

Untuk menemukan cookie tertentu, kita dapat memisahkan

document.cookie = "user=John"; // update only cookie named 'user'
alert(document.cookie); // show all cookies
6 dengan
document.cookie = "user=John"; // update only cookie named 'user'
alert(document.cookie); // show all cookies
9, lalu menemukan nama yang tepat. Kita dapat menggunakan ekspresi reguler atau fungsi array untuk melakukan itu

Kami meninggalkannya sebagai latihan untuk pembaca. Selain itu, di akhir bab ini Anda akan menemukan fungsi pembantu untuk memanipulasi cookie

Kami dapat menulis ke

document.cookie = "user=John"; // update only cookie named 'user'
alert(document.cookie); // show all cookies
6. Tapi itu bukan properti data, ini adalah pengakses (pengambil/penyetel). Tugas untuk itu diperlakukan secara khusus

Operasi tulis ke

document.cookie = "user=John"; // update only cookie named 'user'
alert(document.cookie); // show all cookies
_6 hanya memperbarui cookie yang disebutkan di dalamnya, tetapi tidak menyentuh cookie lain

Misalnya, panggilan ini menyetel cookie dengan nama

// special characters (spaces), need encoding
let name = "my name";
let value = "John Smith"

// encodes the cookie as my%20name=John%20Smith
document.cookie = encodeURIComponent(name) + '=' + encodeURIComponent(value);

alert(document.cookie); // ...; my%20name=John%20Smith
4 dan nilai
// special characters (spaces), need encoding
let name = "my name";
let value = "John Smith"

// encodes the cookie as my%20name=John%20Smith
document.cookie = encodeURIComponent(name) + '=' + encodeURIComponent(value);

alert(document.cookie); // ...; my%20name=John%20Smith
5

document.cookie = "user=John"; // update only cookie named 'user'
alert(document.cookie); // show all cookies

Jika Anda menjalankannya, mungkin Anda akan melihat banyak cookie. Itu karena operasi

// special characters (spaces), need encoding
let name = "my name";
let value = "John Smith"

// encodes the cookie as my%20name=John%20Smith
document.cookie = encodeURIComponent(name) + '=' + encodeURIComponent(value);

alert(document.cookie); // ...; my%20name=John%20Smith
6 tidak menimpa semua cookie. Itu hanya menetapkan cookie yang disebutkan
// special characters (spaces), need encoding
let name = "my name";
let value = "John Smith"

// encodes the cookie as my%20name=John%20Smith
document.cookie = encodeURIComponent(name) + '=' + encodeURIComponent(value);

alert(document.cookie); // ...; my%20name=John%20Smith
4

Secara teknis, nama dan nilai dapat memiliki karakter apa saja. Untuk mempertahankan pemformatan yang valid, format tersebut harus di-escape menggunakan fungsi ________13______8 bawaan

// special characters (spaces), need encoding
let name = "my name";
let value = "John Smith"

// encodes the cookie as my%20name=John%20Smith
document.cookie = encodeURIComponent(name) + '=' + encodeURIComponent(value);

alert(document.cookie); // ...; my%20name=John%20Smith

Keterbatasan

Ada beberapa batasan

  • Pasangan
    document.cookie = "user=John"; // update only cookie named 'user'
    alert(document.cookie); // show all cookies
    8, setelah
    // special characters (spaces), need encoding
    let name = "my name";
    let value = "John Smith"
    
    // encodes the cookie as my%20name=John%20Smith
    document.cookie = encodeURIComponent(name) + '=' + encodeURIComponent(value);
    
    alert(document.cookie); // ...; my%20name=John%20Smith
    8, tidak boleh melebihi 4KB. Jadi kami tidak dapat menyimpan sesuatu yang besar dalam cookie
  • Jumlah total cookie per domain dibatasi sekitar 20+, batas pastinya tergantung pada browser

Cookie memiliki beberapa opsi, banyak di antaranya penting dan harus disetel

Opsi dicantumkan setelah

document.cookie = "user=John; path=/; expires=Tue, 19 Jan 2038 03:14:07 GMT"
_1, dibatasi oleh
document.cookie = "user=John"; // update only cookie named 'user'
alert(document.cookie); // show all cookies
9, seperti ini

document.cookie = "user=John; path=/; expires=Tue, 19 Jan 2038 03:14:07 GMT"

  • document.cookie = "user=John; path=/; expires=Tue, 19 Jan 2038 03:14:07 GMT"
    _3

Awalan jalur url harus mutlak. Itu membuat cookie dapat diakses untuk halaman di bawah jalur itu. Secara default, ini adalah jalur saat ini

Jika cookie disetel dengan

document.cookie = "user=John; path=/; expires=Tue, 19 Jan 2038 03:14:07 GMT"
_4, cookie terlihat di halaman
document.cookie = "user=John; path=/; expires=Tue, 19 Jan 2038 03:14:07 GMT"
5 dan
document.cookie = "user=John; path=/; expires=Tue, 19 Jan 2038 03:14:07 GMT"
6, tetapi tidak di
document.cookie = "user=John; path=/; expires=Tue, 19 Jan 2038 03:14:07 GMT"
7 atau
document.cookie = "user=John; path=/; expires=Tue, 19 Jan 2038 03:14:07 GMT"
8

Biasanya, kita harus mengatur

document.cookie = "user=John; path=/; expires=Tue, 19 Jan 2038 03:14:07 GMT"
_9 ke root.
// if we set a cookie at site.com website...
document.cookie = "user=John"

// ...we won't see it at forum.site.com
alert(document.cookie); // no user
0 untuk membuat cookie dapat diakses dari semua halaman situs web

  • // if we set a cookie at site.com website...
    document.cookie = "user=John"
    
    // ...we won't see it at forum.site.com
    alert(document.cookie); // no user
    _1

Domain menentukan di mana cookie dapat diakses. Namun dalam praktiknya, ada batasannya. Kami tidak dapat menetapkan domain apa pun

Tidak ada cara untuk membiarkan cookie dapat diakses dari domain tingkat 2 lainnya, jadi

// if we set a cookie at site.com website...
document.cookie = "user=John"

// ...we won't see it at forum.site.com
alert(document.cookie); // no user
2 tidak akan pernah menerima kumpulan cookie di
// if we set a cookie at site.com website...
document.cookie = "user=John"

// ...we won't see it at forum.site.com
alert(document.cookie); // no user
3

Ini adalah batasan keamanan, untuk memungkinkan kami menyimpan data sensitif dalam cookie yang seharusnya hanya tersedia di satu situs

Secara default, cookie hanya dapat diakses di domain yang menyetelnya

Harap dicatat, secara default cookie juga tidak dibagikan ke subdomain, seperti

// if we set a cookie at site.com website...
document.cookie = "user=John"

// ...we won't see it at forum.site.com
alert(document.cookie); // no user
4

// if we set a cookie at site.com website...
document.cookie = "user=John"

// ...we won't see it at forum.site.com
alert(document.cookie); // no user

…Tapi ini bisa diubah. Jika kami ingin mengizinkan subdomain seperti

// if we set a cookie at site.com website...
document.cookie = "user=John"

// ...we won't see it at forum.site.com
alert(document.cookie); // no user
4 untuk mendapatkan set cookie di
// if we set a cookie at site.com website...
document.cookie = "user=John"

// ...we won't see it at forum.site.com
alert(document.cookie); // no user
3, itu mungkin

Agar hal itu terjadi, saat menyetel cookie di

// if we set a cookie at site.com website...
document.cookie = "user=John"

// ...we won't see it at forum.site.com
alert(document.cookie); // no user
3, kita harus secara eksplisit menyetel opsi
// if we set a cookie at site.com website...
document.cookie = "user=John"

// ...we won't see it at forum.site.com
alert(document.cookie); // no user
8 ke domain root.
// if we set a cookie at site.com website...
document.cookie = "user=John"

// ...we won't see it at forum.site.com
alert(document.cookie); // no user
_1. Kemudian semua subdomain akan melihat cookie tersebut

Misalnya

// at site.com
// make the cookie accessible on any subdomain *.site.com:
document.cookie = "user=John; domain=site.com"

// later

// at forum.site.com
alert(document.cookie); // has cookie user=John

Untuk alasan historis,

// at site.com
// make the cookie accessible on any subdomain *.site.com:
document.cookie = "user=John; domain=site.com"

// later

// at forum.site.com
alert(document.cookie); // has cookie user=John
0 (dengan titik sebelum
// if we set a cookie at site.com website...
document.cookie = "user=John"

// ...we won't see it at forum.site.com
alert(document.cookie); // no user
3) juga berfungsi dengan cara yang sama, memungkinkan akses ke cookie dari subdomain. Itu notasi lama dan harus digunakan jika kita perlu mendukung browser yang sangat lama

Singkatnya, opsi

// if we set a cookie at site.com website...
document.cookie = "user=John"

// ...we won't see it at forum.site.com
alert(document.cookie); // no user
_8 memungkinkan untuk membuat cookie dapat diakses di subdomain

Secara default, jika cookie tidak memiliki salah satu opsi ini, cookie akan menghilang saat browser ditutup. Cookie semacam itu disebut "cookie sesi"

Untuk membiarkan cookie bertahan dari penutupan browser, kita dapat mengatur opsi

// at site.com
// make the cookie accessible on any subdomain *.site.com:
document.cookie = "user=John; domain=site.com"

// later

// at forum.site.com
alert(document.cookie); // has cookie user=John
3 atau
// at site.com
// make the cookie accessible on any subdomain *.site.com:
document.cookie = "user=John; domain=site.com"

// later

// at forum.site.com
alert(document.cookie); // has cookie user=John
4

  • // at site.com
    // make the cookie accessible on any subdomain *.site.com:
    document.cookie = "user=John; domain=site.com"
    
    // later
    
    // at forum.site.com
    alert(document.cookie); // has cookie user=John
    5

Tanggal kedaluwarsa cookie menentukan waktu, kapan browser akan menghapusnya secara otomatis

Tanggal harus persis dalam format ini, dalam zona waktu GMT. Kita dapat menggunakan

// at site.com
// make the cookie accessible on any subdomain *.site.com:
document.cookie = "user=John; domain=site.com"

// later

// at forum.site.com
alert(document.cookie); // has cookie user=John
_6 untuk mendapatkannya. Misalnya, kami dapat mengatur cookie untuk kedaluwarsa dalam 1 hari

// +1 day from now
let date = new Date(Date.now() + 86400e3);
date = date.toUTCString();
document.cookie = "user=John; expires=" + date;

Jika kami menyetel

// at site.com
// make the cookie accessible on any subdomain *.site.com:
document.cookie = "user=John; domain=site.com"

// later

// at forum.site.com
alert(document.cookie); // has cookie user=John
_3 ke tanggal di masa lalu, cookie akan dihapus

  • // at site.com
    // make the cookie accessible on any subdomain *.site.com:
    document.cookie = "user=John; domain=site.com"
    
    // later
    
    // at forum.site.com
    alert(document.cookie); // has cookie user=John
    8

Ini adalah alternatif untuk

// at site.com
// make the cookie accessible on any subdomain *.site.com:
document.cookie = "user=John; domain=site.com"

// later

// at forum.site.com
alert(document.cookie); // has cookie user=John
_3 dan menentukan kedaluwarsa cookie dalam hitungan detik dari saat ini

Jika disetel ke nol atau nilai negatif, cookie akan dihapus

// cookie will die in +1 hour from now
document.cookie = "user=John; max-age=3600";

// delete cookie (let it expire right now)
document.cookie = "user=John; max-age=0";

  • // +1 day from now
    let date = new Date(Date.now() + 86400e3);
    date = date.toUTCString();
    document.cookie = "user=John; expires=" + date;
    0

Cookie harus ditransfer hanya melalui HTTPS

Secara default, jika kami menyetel cookie di

// +1 day from now
let date = new Date(Date.now() + 86400e3);
date = date.toUTCString();
document.cookie = "user=John; expires=" + date;
1, maka cookie itu juga muncul di
// +1 day from now
let date = new Date(Date.now() + 86400e3);
date = date.toUTCString();
document.cookie = "user=John; expires=" + date;
2 dan sebaliknya

Artinya, cookie berbasis domain, mereka tidak membedakan antara protokol

Dengan opsi ini, jika cookie disetel oleh

// +1 day from now
let date = new Date(Date.now() + 86400e3);
date = date.toUTCString();
document.cookie = "user=John; expires=" + date;
2, maka cookie tersebut tidak akan muncul saat situs yang sama diakses melalui HTTP, seperti
// +1 day from now
let date = new Date(Date.now() + 86400e3);
date = date.toUTCString();
document.cookie = "user=John; expires=" + date;
1. Jadi, jika cookie memiliki konten sensitif yang tidak boleh dikirim melalui HTTP yang tidak dienkripsi, flag
// +1 day from now
let date = new Date(Date.now() + 86400e3);
date = date.toUTCString();
document.cookie = "user=John; expires=" + date;
0 adalah hal yang tepat

// assuming we're on https:// now
// set the cookie to be secure (only accessible over HTTPS)
document.cookie = "user=John; secure";

Itu atribut keamanan lainnya

// +1 day from now
let date = new Date(Date.now() + 86400e3);
date = date.toUTCString();
document.cookie = "user=John; expires=" + date;
6. Ini dirancang untuk melindungi dari apa yang disebut serangan XSRF (pemalsuan permintaan lintas situs).

Untuk memahami cara kerjanya dan kapan berguna, mari kita lihat serangan XSRF

Bayangkan, Anda masuk ke situs ________51______7. Itu adalah. Anda memiliki cookie otentikasi dari situs itu. Browser Anda mengirimkannya ke

// +1 day from now
let date = new Date(Date.now() + 86400e3);
date = date.toUTCString();
document.cookie = "user=John; expires=" + date;
7 dengan setiap permintaan, sehingga mengenali Anda dan melakukan semua operasi keuangan yang sensitif

Sekarang, saat menjelajah web di jendela lain, Anda secara tidak sengaja membuka situs lain

// +1 day from now
let date = new Date(Date.now() + 86400e3);
date = date.toUTCString();
document.cookie = "user=John; expires=" + date;
9. Situs itu memiliki kode JavaScript yang mengirimkan formulir
// cookie will die in +1 hour from now
document.cookie = "user=John; max-age=3600";

// delete cookie (let it expire right now)
document.cookie = "user=John; max-age=0";
0 ke
// +1 day from now
let date = new Date(Date.now() + 86400e3);
date = date.toUTCString();
document.cookie = "user=John; expires=" + date;
7 dengan bidang yang memulai transaksi ke akun peretas

Browser mengirimkan cookie setiap kali Anda mengunjungi situs ________ 51 _______7, bahkan jika formulir dikirimkan dari ________ 51 _______9. Jadi bank mengenali Anda dan benar-benar melakukan pembayaran

Itulah yang disebut serangan "Pemalsuan Permintaan Lintas Situs" (singkatnya, XSRF).

Bank nyata dilindungi darinya tentu saja. Semua formulir yang dihasilkan oleh

// +1 day from now
let date = new Date(Date.now() + 86400e3);
date = date.toUTCString();
document.cookie = "user=John; expires=" + date;
7 memiliki bidang khusus, yang disebut "token perlindungan XSRF", yang tidak dapat dibuat atau diekstraksi oleh halaman jahat dari halaman jarak jauh. Itu bisa mengirimkan formulir di sana, tetapi tidak bisa mendapatkan datanya kembali. Situs
// +1 day from now
let date = new Date(Date.now() + 86400e3);
date = date.toUTCString();
document.cookie = "user=John; expires=" + date;
_7 memeriksa token tersebut dalam setiap formulir yang diterimanya

Perlindungan semacam itu membutuhkan waktu untuk diterapkan. Kami perlu memastikan bahwa setiap formulir memiliki bidang token yang diperlukan, dan kami juga harus memeriksa semua permintaan

Opsi cookie ________ 51 _______ 6 menyediakan cara lain untuk melindungi dari serangan semacam itu, yang (secara teori) seharusnya tidak memerlukan "token perlindungan csrf"

Ini memiliki dua nilai yang mungkin

  • // cookie will die in +1 hour from now
    document.cookie = "user=John; max-age=3600";
    
    // delete cookie (let it expire right now)
    document.cookie = "user=John; max-age=0";
    7 (sama seperti
    // +1 day from now
    let date = new Date(Date.now() + 86400e3);
    date = date.toUTCString();
    document.cookie = "user=John; expires=" + date;
    6 tanpa nilai)

Cookie dengan

// cookie will die in +1 hour from now
document.cookie = "user=John; max-age=3600";

// delete cookie (let it expire right now)
document.cookie = "user=John; max-age=0";
_7 tidak pernah dikirim jika pengguna berasal dari luar situs yang sama

Dengan kata lain, apakah pengguna mengikuti tautan dari email mereka atau mengirimkan formulir dari

// +1 day from now
let date = new Date(Date.now() + 86400e3);
date = date.toUTCString();
document.cookie = "user=John; expires=" + date;
9, atau melakukan operasi apa pun yang berasal dari domain lain, cookie tidak dikirim

Jika cookie otentikasi memiliki opsi

// +1 day from now
let date = new Date(Date.now() + 86400e3);
date = date.toUTCString();
document.cookie = "user=John; expires=" + date;
_6, maka serangan XSRF tidak memiliki peluang untuk berhasil, karena pengiriman dari
// +1 day from now
let date = new Date(Date.now() + 86400e3);
date = date.toUTCString();
document.cookie = "user=John; expires=" + date;
9 datang tanpa cookie. Jadi
// +1 day from now
let date = new Date(Date.now() + 86400e3);
date = date.toUTCString();
document.cookie = "user=John; expires=" + date;
_7 tidak akan mengenali pengguna dan tidak akan melanjutkan pembayaran

Perlindungannya cukup andal. Hanya operasi yang berasal dari

// +1 day from now
let date = new Date(Date.now() + 86400e3);
date = date.toUTCString();
document.cookie = "user=John; expires=" + date;
_7 yang akan mengirimkan cookie
// +1 day from now
let date = new Date(Date.now() + 86400e3);
date = date.toUTCString();
document.cookie = "user=John; expires=" + date;
6, e. g. pengiriman formulir dari halaman lain di
// +1 day from now
let date = new Date(Date.now() + 86400e3);
date = date.toUTCString();
document.cookie = "user=John; expires=" + date;
7

Meskipun, ada sedikit ketidaknyamanan

Saat pengguna mengikuti tautan resmi ke

// +1 day from now
let date = new Date(Date.now() + 86400e3);
date = date.toUTCString();
document.cookie = "user=John; expires=" + date;
_7, seperti dari catatan mereka sendiri, mereka akan terkejut bahwa
// +1 day from now
let date = new Date(Date.now() + 86400e3);
date = date.toUTCString();
document.cookie = "user=John; expires=" + date;
7 tidak mengenalinya. Memang,
// cookie will die in +1 hour from now
document.cookie = "user=John; max-age=3600";

// delete cookie (let it expire right now)
document.cookie = "user=John; max-age=0";
7 cookie tidak dikirim dalam kasus tersebut

Kami dapat mengatasinya dengan menggunakan dua cookie. satu untuk "pengakuan umum", hanya untuk tujuan mengatakan. “Halo, John”, dan yang lainnya untuk operasi pengubahan data dengan

// cookie will die in +1 hour from now
document.cookie = "user=John; max-age=3600";

// delete cookie (let it expire right now)
document.cookie = "user=John; max-age=0";
7. Kemudian, seseorang yang datang dari luar situs akan melihat sambutan, tetapi pembayaran harus dilakukan dari situs web bank, agar cookie kedua dikirim

  • // returns the cookie with the given name,
    // or undefined if not found
    function getCookie(name) {
      let matches = document.cookie.match(new RegExp(
        "(?:^|; )" + name.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g, '\\$1') + "=([^;]*)"
      ));
      return matches ? decodeURIComponent(matches[1]) : undefined;
    }
    _1

Pendekatan yang lebih santai yang juga melindungi dari XSRF dan tidak merusak pengalaman pengguna

Mode longgar, seperti

// returns the cookie with the given name,
// or undefined if not found
function getCookie(name) {
  let matches = document.cookie.match(new RegExp(
    "(?:^|; )" + name.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g, '\\$1') + "=([^;]*)"
  ));
  return matches ? decodeURIComponent(matches[1]) : undefined;
}
2, melarang browser mengirim cookie ketika datang dari luar situs, tetapi menambahkan pengecualian

Cookie

// returns the cookie with the given name,
// or undefined if not found
function getCookie(name) {
  let matches = document.cookie.match(new RegExp(
    "(?:^|; )" + name.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g, '\\$1') + "=([^;]*)"
  ));
  return matches ? decodeURIComponent(matches[1]) : undefined;
}
1 dikirim jika kedua kondisi ini benar

  1. Metode HTTP "aman" (mis. g. DAPATKAN, tetapi bukan POST)

    Daftar lengkap metode HTTP aman ada di spesifikasi RFC7231. Pada dasarnya, ini adalah metode yang harus digunakan untuk membaca, bukan menulis data. Mereka tidak boleh melakukan operasi pengubahan data apa pun. Mengikuti tautan selalu DAPATKAN, metode yang aman

  2. Operasi melakukan navigasi tingkat atas (mengubah URL di bilah alamat browser)

    Itu biasanya benar, tetapi jika navigasi dilakukan di

    // returns the cookie with the given name,
    // or undefined if not found
    function getCookie(name) {
      let matches = document.cookie.match(new RegExp(
        "(?:^|; )" + name.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g, '\\$1') + "=([^;]*)"
      ));
      return matches ? decodeURIComponent(matches[1]) : undefined;
    }
    4, maka itu bukan tingkat atas. Selain itu, metode JavaScript untuk permintaan jaringan tidak melakukan navigasi apa pun, sehingga tidak cocok

Jadi, apa yang dilakukan

// returns the cookie with the given name,
// or undefined if not found
function getCookie(name) {
  let matches = document.cookie.match(new RegExp(
    "(?:^|; )" + name.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g, '\\$1') + "=([^;]*)"
  ));
  return matches ? decodeURIComponent(matches[1]) : undefined;
}
_1, pada dasarnya adalah mengizinkan operasi "masuk ke URL" yang paling umum untuk memiliki cookie. e. g. membuka tautan situs web dari catatan yang memenuhi ketentuan ini

Tetapi apa pun yang lebih rumit, seperti permintaan jaringan dari situs lain atau pengiriman formulir, akan kehilangan cookie

Jika itu baik untuk Anda, menambahkan

// returns the cookie with the given name,
// or undefined if not found
function getCookie(name) {
  let matches = document.cookie.match(new RegExp(
    "(?:^|; )" + name.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g, '\\$1') + "=([^;]*)"
  ));
  return matches ? decodeURIComponent(matches[1]) : undefined;
}
1 mungkin tidak akan merusak pengalaman pengguna dan menambahkan perlindungan

Secara keseluruhan,

// +1 day from now
let date = new Date(Date.now() + 86400e3);
date = date.toUTCString();
document.cookie = "user=John; expires=" + date;
_6 adalah pilihan yang bagus

Ada kekurangannya

  • // +1 day from now
    let date = new Date(Date.now() + 86400e3);
    date = date.toUTCString();
    document.cookie = "user=John; expires=" + date;
    6 diabaikan (tidak didukung) oleh browser yang sangat lama, sekitar tahun 2017

Jadi jika kita hanya mengandalkan

// +1 day from now
let date = new Date(Date.now() + 86400e3);
date = date.toUTCString();
document.cookie = "user=John; expires=" + date;
_6 untuk memberikan perlindungan, maka browser lama akan rentan

Tapi kita pasti bisa menggunakan

// +1 day from now
let date = new Date(Date.now() + 86400e3);
date = date.toUTCString();
document.cookie = "user=John; expires=" + date;
_6 bersama dengan langkah-langkah perlindungan lainnya, seperti token xsrf, untuk menambahkan lapisan pertahanan tambahan dan kemudian, di masa mendatang, ketika browser lama mati, kita mungkin bisa menjatuhkan token xsrf

Opsi ini tidak ada hubungannya dengan JavaScript, tetapi kami harus menyebutkannya untuk kelengkapan

Server web menggunakan header

document.cookie = "user=John"; // update only cookie named 'user'
alert(document.cookie); // show all cookies
_2 untuk menyetel cookie. Juga, ini dapat mengatur opsi
document.cookie = "user=John"; // update only cookie named 'user'
alert(document.cookie); // show all cookies
_02

Opsi ini melarang akses JavaScript apa pun ke cookie. Kami tidak dapat melihat cookie tersebut atau memanipulasinya menggunakan

document.cookie = "user=John"; // update only cookie named 'user'
alert(document.cookie); // show all cookies
6

Itu digunakan sebagai tindakan pencegahan, untuk melindungi dari serangan tertentu saat peretas menyuntikkan kode JavaScript miliknya sendiri ke halaman dan menunggu pengguna mengunjungi halaman tersebut. Itu sama sekali tidak mungkin, peretas seharusnya tidak dapat menyuntikkan kode mereka ke situs kami, tetapi mungkin ada bug yang memungkinkan mereka melakukannya

Biasanya, jika hal seperti itu terjadi, dan pengguna mengunjungi halaman web dengan kode JavaScript peretas, maka kode tersebut akan dieksekusi dan mendapatkan akses ke

document.cookie = "user=John"; // update only cookie named 'user'
alert(document.cookie); // show all cookies
6 dengan cookie pengguna yang berisi informasi autentikasi. Itu buruk

Tetapi jika cookie adalah

document.cookie = "user=John"; // update only cookie named 'user'
alert(document.cookie); // show all cookies
02, maka
document.cookie = "user=John"; // update only cookie named 'user'
alert(document.cookie); // show all cookies
6 tidak melihatnya, jadi itu dilindungi

Berikut sekumpulan kecil fungsi untuk bekerja dengan cookie, lebih nyaman daripada modifikasi manual

document.cookie = "user=John"; // update only cookie named 'user'
alert(document.cookie); // show all cookies
6

Ada banyak pustaka cookie untuk itu, jadi ini untuk tujuan demo. Meskipun bekerja penuh

Cara terpendek untuk mengakses cookie adalah dengan menggunakan ekspresi reguler

Fungsi

document.cookie = "user=John"; // update only cookie named 'user'
alert(document.cookie); // show all cookies
08 mengembalikan cookie dengan
document.cookie = "user=John"; // update only cookie named 'user'
alert(document.cookie); // show all cookies
09 yang diberikan

// returns the cookie with the given name,
// or undefined if not found
function getCookie(name) {
  let matches = document.cookie.match(new RegExp(
    "(?:^|; )" + name.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g, '\\$1') + "=([^;]*)"
  ));
  return matches ? decodeURIComponent(matches[1]) : undefined;
}

Di sini

document.cookie = "user=John"; // update only cookie named 'user'
alert(document.cookie); // show all cookies
10 dihasilkan secara dinamis, untuk mencocokkan
document.cookie = "user=John"; // update only cookie named 'user'
alert(document.cookie); // show all cookies
11

Harap perhatikan bahwa nilai cookie dikodekan, jadi

document.cookie = "user=John"; // update only cookie named 'user'
alert(document.cookie); // show all cookies
12 menggunakan fungsi
document.cookie = "user=John"; // update only cookie named 'user'
alert(document.cookie); // show all cookies
13 bawaan untuk mendekodekannya

Setel

document.cookie = "user=John"; // update only cookie named 'user'
alert(document.cookie); // show all cookies
09 cookie ke
document.cookie = "user=John"; // update only cookie named 'user'
alert(document.cookie); // show all cookies
15 yang diberikan dengan
// if we set a cookie at site.com website...
document.cookie = "user=John"

// ...we won't see it at forum.site.com
alert(document.cookie); // no user
0 secara default (dapat dimodifikasi untuk menambahkan default lainnya)

document.cookie = "user=John"; // update only cookie named 'user'
alert(document.cookie); // show all cookies
0

Untuk menghapus cookie, kita bisa menyebutnya dengan tanggal kedaluwarsa negatif

document.cookie = "user=John"; // update only cookie named 'user'
alert(document.cookie); // show all cookies
_1

Memperbarui atau menghapus harus menggunakan jalur dan domain yang sama

Tolong dicatat. saat kami memperbarui atau menghapus cookie, kami harus menggunakan jalur dan opsi domain yang persis sama seperti saat kami menyetelnya

Bersama. Kue kering. js

Cookie disebut "pihak ketiga" jika ditempatkan oleh domain selain halaman yang dikunjungi pengguna

Contohnya

  1. Laman di

    // if we set a cookie at site.com website...
    document.cookie = "user=John"
    
    // ...we won't see it at forum.site.com
    alert(document.cookie); // no user
    _3 memuat spanduk dari situs lain.
    document.cookie = "user=John"; // update only cookie named 'user'
    alert(document.cookie); // show all cookies
    _18

  2. Bersamaan dengan spanduk, server jarak jauh di

    document.cookie = "user=John"; // update only cookie named 'user'
    alert(document.cookie); // show all cookies
    _19 dapat menyetel tajuk
    document.cookie = "user=John"; // update only cookie named 'user'
    alert(document.cookie); // show all cookies
    2 dengan cookie seperti
    document.cookie = "user=John"; // update only cookie named 'user'
    alert(document.cookie); // show all cookies
    21. Cookie tersebut berasal dari domain
    document.cookie = "user=John"; // update only cookie named 'user'
    alert(document.cookie); // show all cookies
    _19, dan hanya akan terlihat di
    document.cookie = "user=John"; // update only cookie named 'user'
    alert(document.cookie); // show all cookies
    19

  3. Lain kali ketika

    document.cookie = "user=John"; // update only cookie named 'user'
    alert(document.cookie); // show all cookies
    _19 diakses, server jarak jauh mendapatkan cookie
    document.cookie = "user=John"; // update only cookie named 'user'
    alert(document.cookie); // show all cookies
    25 dan mengenali pengguna

  4. Yang lebih penting adalah, saat pengguna berpindah dari

    // if we set a cookie at site.com website...
    document.cookie = "user=John"
    
    // ...we won't see it at forum.site.com
    alert(document.cookie); // no user
    3 ke situs lain
    // if we set a cookie at site.com website...
    document.cookie = "user=John"
    
    // ...we won't see it at forum.site.com
    alert(document.cookie); // no user
    2, yang juga memiliki spanduk, lalu
    document.cookie = "user=John"; // update only cookie named 'user'
    alert(document.cookie); // show all cookies
    19 mendapatkan cookie, karena itu milik
    document.cookie = "user=John"; // update only cookie named 'user'
    alert(document.cookie); // show all cookies
    19, sehingga mengenali pengunjung dan melacaknya saat dia berpindah antar situs

Cookie pihak ketiga secara tradisional digunakan untuk pelacakan dan layanan iklan, karena sifatnya. Mereka terikat ke domain asal, jadi

document.cookie = "user=John"; // update only cookie named 'user'
alert(document.cookie); // show all cookies
19 dapat melacak pengguna yang sama di antara situs yang berbeda, jika mereka semua mengaksesnya

Secara alami, beberapa orang tidak suka dilacak, jadi browser memungkinkan untuk menonaktifkan cookie semacam itu

Selain itu, beberapa browser modern menggunakan kebijakan khusus untuk cookie tersebut

  • Safari sama sekali tidak mengizinkan cookie pihak ketiga
  • Firefox hadir dengan "daftar hitam" domain pihak ketiga yang memblokir cookie pihak ketiga

Tolong dicatat

Jika kami memuat skrip dari domain pihak ketiga, seperti

document.cookie = "user=John"; // update only cookie named 'user'
alert(document.cookie); // show all cookies
31, dan skrip itu menggunakan
document.cookie = "user=John"; // update only cookie named 'user'
alert(document.cookie); // show all cookies
6 untuk menyetel cookie, maka cookie tersebut bukan pihak ketiga

Jika skrip menyetel cookie, dari mana pun skrip itu berasal – cookie tersebut milik domain halaman web saat ini

Topik ini sama sekali tidak terkait dengan JavaScript, hanya sesuatu yang perlu diingat saat menyetel cookie

Ada undang-undang di Eropa yang disebut GDPR, yang memberlakukan seperangkat aturan bagi situs web untuk menghormati privasi pengguna. Salah satu aturan ini adalah meminta izin eksplisit untuk melacak cookie dari pengguna

Harap perhatikan, itu hanya tentang melacak/mengidentifikasi/mengotorisasi cookie

Jadi, jika kami menyetel cookie yang hanya menyimpan beberapa informasi, tetapi tidak melacak atau mengidentifikasi pengguna, maka kami bebas melakukannya

Tetapi jika kita akan menyetel cookie dengan sesi autentikasi atau id pelacakan, maka pengguna harus mengizinkannya

Situs web umumnya memiliki dua varian mengikuti GDPR. Anda pasti sudah melihat keduanya di web

  1. Jika situs web ingin menyetel cookie pelacakan hanya untuk pengguna yang diautentikasi

    Untuk melakukannya, formulir pendaftaran harus memiliki kotak centang seperti "terima kebijakan privasi" (yang menjelaskan bagaimana cookie digunakan), pengguna harus mencentangnya, lalu situs web bebas menyetel cookie autentikasi

  2. Jika situs web ingin menyetel cookie pelacakan untuk semua orang

    Untuk melakukannya secara legal, sebuah situs web menampilkan modal “splash screen” untuk pendatang baru, dan mengharuskan mereka untuk menyetujui cookie. Kemudian situs web dapat mengaturnya dan membiarkan orang melihat kontennya. Itu bisa mengganggu pengunjung baru sekalipun. Tidak ada yang suka melihat layar splash modal "harus-klik" seperti itu daripada kontennya. Tetapi GDPR membutuhkan perjanjian eksplisit

GDPR bukan hanya tentang cookie, ini juga tentang masalah terkait privasi lainnya, tetapi itu terlalu jauh di luar jangkauan kami

Buat Cookie dengan JavaScript . dokumen. cookie = "username=John Doe"; .
Setel cookie .
dokumen. cookie adalah perintah yang digunakan untuk membuat cookie baru
'newCookie' adalah string yang menetapkan nilai cookie. Ini memiliki sintaksnya sendiri yang harus diperhatikan. nama=nilai. Untuk alasan keterbacaan, nama harus menyiratkan apa yang disimpan cookie (mis. g. nama pengguna) nilai hanyalah nilai
Cukup setel header Set-Cookie sebagai respons dari kode sisi server . Browser harus menyimpannya secara otomatis. Sebagai pengembang, Anda mungkin dapat memeriksa nilai cookie menggunakan "Alat Pengembang". Dan cookie yang sama akan dikirim dalam permintaan berikutnya ke domain yang sama, hingga cookie kedaluwarsa.
untuk mengambil nilai cookie tertentu, kita hanya perlu mendapatkan string setelah "; {name}=" dan sebelum next ";". Before we do any processing, we prepend the cookies string with "; ", so that every cookie name, including the first one, is enclosed with "; " and "=": "; {name}={value}; {name}={value}; ..."