前言
前端頁面之間需要傳遞資料時,網址參數能解決大部分問題;但遇到需要跨頁保留、且會反覆變動的狀態(例如從 A 頁選收貨地址、到 B 頁確認、再回 A 頁帶回結果),Cookie 往往是更省事的做法。
以下把讀、寫、刪三件事各自封裝成獨立函式,方便直接複用到專案裡。
/**
* 設定 Cookie
* @param name 屬性名
* @param value 屬性值
* @param time 有效時間(毫秒)
*/
function setCookie(name, value, time) {
time = time ? parseFloat(time) : 0;
var exp = new Date();
exp.setTime(exp.getTime() + time);
// escape 已過時,改用 encodeURIComponent
document.cookie = name + "=" + encodeURIComponent(value)
+ ";expires=" + (time ? exp.toGMTString() : 'session');
}
/**
* 取得 Cookie,找不到時回傳 null
*/
function getCookie(name) {
var arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;)");
if (arr = document.cookie.match(reg))
// unescape 已過時,改用 decodeURIComponent
return decodeURIComponent(arr[2]);
else
return null;
}
/**
* 刪除 Cookie:把過期時間設為過去即可失效
*/
function delCookie(name) {
var exp = new Date();
exp.setTime(exp.getTime() - 1);
var cval = getCookie(name);
if (cval != null)
document.cookie = name + "=" + cval + ";expires=" + exp.toGMTString();
}
Cookie 預設綁定在特定網域下,因此跨站同步需要透過 domain 屬性與一層跳板頁面來完成。
// 寫入時可一併指定 domain 與 path
document.cookie = "name=" + "value;"
+ "expires=" + "datatime;"
+ "domain=" + "" + "path=" + "/path" + "; secure";
// 用隱藏 iframe 觸發另一個站點的頁面
<iframe src="https://網站:1234/test/Index" width="100" height="100"
style="display:none"></iframe>
// 原頁面把 cookie 帶到另一個站
window.location = "https://另外一個網站:1234/GetCookie/Index?" + document.cookie;
// 目標站解析網址並寫入自己的 cookie
var url = window.location.toString();
var get = url.substring(url.indexOf("liuph"));
var idx = get.indexOf("=");
if (idx != -1) {
var name = get.substring(0, idx);
var val = get.substring(idx + 1);
setCookie(name, val, 1);
}
需要留意的是,把 Cookie 內容放進網址查詢字串會暴露在伺服器日誌與瀏覽器歷史中,正式環境更常見的做法是改用 postMessage、以子網域共用 domain,或乾脆交由後端以 SameSite 設定處理。以上範例適合作為理解原理的起點。