jquery.cookie 是一個體積很小的 Cookie 外掛,讀取、寫入、刪除都能一行搞定。本文整理它的引入方式、常用操作與所有可配置參數。
先載入 jQuery,再載入外掛,順序不可顛倒:
<script type="text/javascript" src="js/jquery-1.6.2.min.js"></script>
<script type="text/javascript" src="js/jquery.cookie.js"></script>
$.cookie('the_cookie', 'the_value');
沒有指定有效時間時,Cookie 的有效期預設到使用者關閉瀏覽器為止,這種稱為工作階段 Cookie(session cookie)。
$.cookie('the_cookie', 'the_value', { expires: 7 });
一旦指明了有效時間,建立的就是持久 Cookie(persistent cookie)。
$.cookie('the_cookie', 'the_value', { expires: 7, path: '/' });
path 的作用要特別注意:預設情況下只有設定 Cookie 的那個網頁能讀取它。若希望一個頁面能讀到另一個頁面設定的 Cookie,就必須指定路徑。把路徑設為網站根目錄可讓所有網頁互相讀取,但一般不建议這麼做,容易造成命名衝突。
$.cookie('the_cookie'); // 存在 => 'the_value'
$.cookie('not_existing'); // 不存在 => null
$.cookie('the_cookie', null); // 刪除
$.cookie('the_cookie', '', { expires: -1 }); // 另一種刪除寫法
path: '/'。若要刪除一個設過 path 的 Cookie,呼叫時必須帶上同一個路徑:$.cookie('the_cookie', null, { path: '/' });raw: true。$.cookie('the_cookie'); // 讀取
$.cookie('the_cookie', 'the_value'); // 設定
$.cookie('the_cookie', 'the_value', { expires: 7 }); // 七天後過期
$.cookie('the_cookie', 'the_value', {
expires: 7, path: '/', domain: '80tvb.com', secure: true
}); // 完整參數
$.cookie('the_cookie', null); // 刪除
讓 Cookie 在 x 分鐘後過期,可以傳入 Date 物件:
var date = new Date();
date.setTime(date.getTime() + (x * 60 * 1000));
$.cookie('example', 'foo', { expires: date });
也可以直接給天數:$.cookie('example', 'foo', { expires: 7 });
有些使用者會停用 Cookie,重要流程前值得先探測一次:
$(document).ready(function() {
var dt = new Date();
dt.setSeconds(dt.getSeconds() + 60);
document.cookie = "cookietest=1; expires=" + dt.toGMTString();
var cookiesenabled = document.cookie.indexOf("cookietest=") != -1;
if (!cookiesenabled) {
// Cookie 不能用,走替代方案
}
});