JavaScript 存取 Cookie

CookieJavaScript 中可以使用語法來設定,將少量的資料合法寫在瀏覽用戶端之電腦檔案內,然後存在瀏覽者(用戶端)的電腦中,Cookie 是一個獨立檔案,存放於例如 Temporary Internet Files 這資料夾內。之後再讓網頁系統取得 Cookie 的值自動填入或判斷。Cookies 可以運用如使用者名稱,密碼或是日期等等之記錄。

並且能在 Cookie 中設定有效時間,即時間過後則失效,增加網頁互動下的資料存取方便。應用上可以如登錄網站時,網站請求用戶輸入用戶名和密碼,並且用戶可以勾選「下次自動登錄」。如果勾選了,於下次訪問網站時,用戶不用再輸入用戶名和密碼就可以自動登錄網站。

Cookie domain

例如於 http://www.eion.com.tw/Blogger/User/login.html 該頁中建立 Cookie,同時把 path=/ 並且 domain=eion.com.tw,則所有在 eion.com.tw 網域的 WWW 站台(如 store.eion.com.tw)都可以讀取此 cookie。

Cookie path

設定可讀取 Cookie 的最上層目錄。若設定 path=/Blogger 則網頁 http://www.eion.com.tw/Blogger/Store/Product.html 就可以讀取此 Cookie。若設定 path=/ 則網站 http://www.eion.com.tw/ 所有網頁中均可以讀取此 Cookie。

Cookie 在預設隱私的規則下 Cookie 只能被設定網頁的「目錄」與其「子目錄」中的其他網頁所讀取。例如網頁 http://www.eion.com.tw/Blogger/User/login.html 建立了一個 Cookie。
則此 Cookie 可以被 http://www.eion.com.tw/Blogger/User/mail.html 或 http://www.eion.com.tw/Blogger/User/Textually/article.html 所讀取,但不能被 http://www.eion.com.tw/Blogger/Store/Product.html 所讀取。也就是可讀取此 Cookie 的最上層目錄為 /Blogger/User。

Cookie HttpOnly

Cookie 設置 HttpOnly 的屬性則不能使用 JavaScript 經由 Document.cookie 屬性、XMLHttpRequest 和 Request API 進行訪問,以防範跨站腳本 XSS 攻擊。

Cookie SameSite 的限制

SameSite 必須加入 Secure Flag 加強資料的保護。在新版本瀏覽器中,Lax:為預設選項 Same-site cookies 將會為一些跨站子請求保留,如圖片加載或者 frames 的調用,但只有當用戶從外部站點導航到 URL 時才會發送。
Strict 為嚴格方式,可以禁止第三方 Cookie 跨站點時的情況下都不會發送 Cookie。只有在當前網頁 URL 與請求網址的目標一致,才會讀取 Cookie 內的記錄以確保安全。


JavaScript Cookie 是在瀏覽器端儲存資料的機制,可以用來記錄使用者的偏好、身份或其他狀態。JavaScript 存取 Cookie 的使用已經不再符合當前的需求和標準,建議使用 Web Storage APIIndexedDB API 來替代它們,以提高網站的效能和安全性。Web Storage API 包括 localStoragesessionStorage 兩種類型,分別用來儲存永久性和臨時性的資料。它們都是以鍵值對的形式儲存資料,並且提供方便的方法來設定或取得資料。



JavaScript Cookie 的使用方式

設定 Set cookie

function doCookieSetup(name, value) {
  const expires = new Date();
  //有效時間保存 2 天 = 2 * 24 * 60 * 60 * 1000
  expires.setTime(expires.getTime() + 172800000);
  document.cookie = name + "=" + escape(value) + ";SameSite=Strict;expires=" + expires.toGMTString()
}

查詢 Get cookie by name

function getCookie(name) {
  let arg = escape(name) + "=";
  let nameLen = arg.length;
  let cookieLen = document.cookie.length;
  let i = 0;
  while (i & lt; cookieLen) {
    let j = i + nameLen;
    if (document.cookie.substring(i, j) == arg) return getCookieValueByIndex(j);
    i = document.cookie.indexOf(" ", i) + 1;
    if (i == 0) break;
  }
  return null;
}

function getCookieValueByIndex(startIndex) {
  let endIndex = document.cookie.indexOf(";", startIndex);
  if (endIndex == -1) endIndex = document.cookie.length;
  return unescape(document.cookie.substring(startIndex, endIndex));
}

刪除 Delete cookie entry

function delCookie(name) {
  let exp = new Date();
  exp.setTime(exp.getTime() - 1);
  let cval = getCookie(name);
  document.cookie = escape(name) + "=" + cval + ";SameSite=Strict;expires=" + exp.toGMTString();
}

Html 的文法

設定 Cookie:

<form>
  Cookie Name: <input name="cName" type="text" />
  Cookie Value: <input name="cValue" type="text" />
  <input onclick="doCookieSetup(this.form.cName.value, this.form.cValue.value)"
  type="button" value="設定" />
</form>
Cookie Name :
Cookie Value :


查詢 Cookie:

<form>
  Cookie Name: <input name="cName" type="text" />
  Cookie Value: <input name="cValue" type="text" />
  <input onclick="this.form.cValue.value=getCookie(this.form.cName.value)"
  type="button" value="查詢" />
</form>
Cookie Name :
Cookie Value :


刪除 Cookie:

<form>
  Cookie Name: <input name="cName" type="text" />
  <input onclick="delCookie(this.form.cName.value)" type="button" value="移除" />
</form>
Cookie Name :


列出全部 Cookie 值

function listCookie() {
  document.write("<table>");
  document.write("<tr><th>Name<th>Value");
  cookieArray = document.cookie.split(";");
  for (let i = 0; i < cookieArray.length; i++) {
    thisCookie = cookieArray[i].split("=");
    cName = unescape(thisCookie[0]);
    cValue = unescape(thisCookie[1]);
    document.write("<tr><td>" + cName + "</td><td>" + cValue + "</td>");
  }
  document.write("</table>");
}
<script>
listCookie();
</script>