原生 cookie 操作全靠字串拼接與切分,寫起來瑣碎又容易出錯。把它包成一個物件,後續所有頁面都能直接呼叫。
document.cookie = "userId=111"; // 最簡單的寫法
// 完整版:可設定網域、路徑、安全性與過期時間
document.cookie = "userId=111;domain=.google.com;path=/;secure;expire="
+ date.toGMTString();
刪除的方式是把過期時間設為過去,瀏覽器就會立即失效該筆資料。
var myCookie = {
get: function (name) {
if (typeof name != "undefined") {
return myCookie_get(name); // 取單一值
}
return myCookie_getAll(); // 取全部
},
add: function (name, value, options) {
myCookie_add(name, value, options);
},
delete: function (name) {
myCookie_add(name, null);
}
};
String.prototype.Trim = function () {
return this.replace(/^\s+/g, "").replace(/\s+$/g, "");
};
/**
* 寫入 cookie
* @param name 名稱,不可為空
* @param value 值;傳 null 代表刪除
* @param options {"expires":..., "path":"/", "domain":..., "secure":...}
*/
function myCookie_add(name, value, options) {
if (typeof value != 'undefined') {
options = options || {};
if (value === null) {
value = '';
options.expires = -1;
}
var expires = '';
if (options.expires &&
(typeof options.expires == 'number' || options.expires.toUTCString)) {
var date;
if (typeof options.expires == 'number') {
date = new Date();
date.setTime(date.getTime() + options.expires * 24 * 60 * 60 * 1000);
} else {
date = options.expires;
}
expires = '; expires=' + date.toUTCString();
}
var path = options.path ? '; path=' + options.path : '';
var domain = options.domain ? '; domain=' + options.domain : '';
var secure = options.secure ? '; secure' : '';
document.cookie = [name, '=', encodeURIComponent(value),
expires, path, domain, secure].join('');
}
}
function myCookie_get(name) {
var cookieValue = null;
if (document.cookie && document.cookie != '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = cookies[i].Trim();
if (cookie.substring(0, name.length + 1) == (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
function myCookie_getAll() {
var cookieArray = [];
if (document.cookie && document.cookie != '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var temp = cookies[i].Trim().split('=');
cookieArray.push('{"name":"' + decodeURIComponent(temp[0])
+ '","value":"' + decodeURIComponent(temp[1]) + '"}');
}
}
return eval('(' + '[' + cookieArray.join(",") + ']' + ')');
}
myCookie.add("useraccount", "admin", { "expires": 5 }); // 有效期限 5 天
alert(myCookie.get("useraccount"));
var cookies = myCookie.get();
for (var i = 0; i < cookies.length; i++) {
alert(cookies[i]["name"] + ":" + cookies[i]["value"]);
}
myCookie.delete("useraccount");
alert(myCookie.get("useraccount"));
getAll 用 eval 解析字串,實務上請改用 JSON.parse;若 cookie 內容可能被使用者竄改,eval 存在執行任意程式碼的風險。String.prototype.Trim 這類寫法容易與其他程式庫衝突,建議改為內部私有函式。ES5 之後已有原生的 String.prototype.trim()。