瀏覽器沒有提供「讀取單一 Cookie」的原生方法,只能拿到一整串以分號分隔的字串自行解析。以下是傳統的 indexOf 做法。
function getCookie(name) {
var offset, cookieValue;
var search = name + "=";
if (document.cookie.length > 0) {
offset = document.cookie.indexOf(search);
if (offset != -1) {
offset += search.length;
var end = document.cookie.indexOf(";", offset);
if (end == -1) end = document.cookie.length;
cookieValue = unescape(document.cookie.substring(offset, end));
}
}
return cookieValue;
}
// name 為 cookie 的鍵名
流程是:組出「name=」當搜尋字串,找到它的位置後往後推,再找下一個分號決定結尾,最後 decode。
前綴誤命中。搜尋 "id=" 時,若 cookie 中同時存在 userid=xxx,indexOf 可能先命中錯誤的那一筆。正確做法是把 cookie 先 split 成陣列再逐筆比對鍵名。
unescape 已棄用。它不會正確處理 UTF-8,中文值會解出亂碼。請改用 decodeURIComponent。
找不到時回傳 undefined 而非空字串。呼叫端若不檢查就會拿到 undefined 參與運算。
function getCookie(name) {
var prefix = name + "=";
var parts = document.cookie ? document.cookie.split('; ') : [];
for (var i = 0; i < parts.length; i++) {
if (parts[i].indexOf(prefix) === 0) {
return decodeURIComponent(parts[i].substring(prefix.length));
}
}
return null;
}
市面上已有 CookieStore API,語意遠比字串解析清楚:
const cookie = await cookieStore.get('name');
if (cookie) console.log(cookie.value);
它支援 Promise、能監聽變化,也能一次取得全部:
cookieStore.addEventListener('change', function (e) {
console.log(e.changed);
});
不過 CookieStore 目前仍限於較新的瀏覽器與安全內容(HTTPS)。在相容性要求高的專案中,與其自己刻,不如引入 js-cookie 這類輕量函式庫,它處理了編碼、路徑、SameSite 與跨瀏覽器差異等細節。
最後一個觀念釐清:JavaScript 只能讀取「非 HttpOnly」的 Cookie。若某個 Cookie 被設定為 HttpOnly,document.cookie 完全看不到它,這不是 bug 而是刻意的安全設計。身份驗證的 session token 就該設成 HttpOnly,以杜絕 XSS 盜取。若你發現讀不到某個 Cookie,請先到開發工具的 Application 面板確認它的 HttpOnly 旗標,而不是急著改 JavaScript。