DIV CSS 佈局教程網

JavaScript 建立與讀取 Cookie 的完整實作
編輯:JavaScript綜合知識     

Cookie 是儲存在使用者電腦中的變數。每當同一台電腦透過瀏覽器請求某個頁面時,就會自動帶上這個 cookie。JavaScript 可以建立它,也可以取回它的值。

常見的使用情境

使用者名稱:當使用者首次拜訪時填入姓名,姓名被存進 cookie。下次再來時,網站就能顯示「歡迎回來,amosli!」——而這個名字正是從 cookie 讀回的。

密碼:同理可儲存密碼以便自動帶入。但這麼做安全性極差,cookie 以純文字形式存放,任何能存取該電腦的人都看得到,實務上絕不應該這樣做。

日期:首次拜訪時把當天日期存起來,下次進站時提示「您上次的訪問是在……」,同樣是從 cookie 取回的。

建立與儲存 Cookie

建立 cookie 其實就是在拼一句字串:

"username=amosli;expires=Mon, 16 Dec 2013 16:20:04 GMT"

然後 document.cookie = 上面的字串 即可。

function setCookie(c_name, value, expiredays) {
  var exdate = new Date();
  exdate.setDate(exdate.getDate() + expiredays);
  document.cookie = c_name + "=" + escape(value)
    + ((expiredays == null) ? "" : ";expires=" + exdate.toGMTString());
}

參數分別是 cookie 的名稱、值與有效天數。函式先把天數轉成有效的日期物件,再把三者組合成字串寫入 document.cookie。

讀取 Cookie

function getCookie(c_name) {
  if (document.cookie.length > 0) {
    c_start = document.cookie.indexOf(c_name + "=");
    if (c_start != -1) {
      c_start = c_start + c_name.length + 1;
      c_end = document.cookie.indexOf(";", c_start);
      if (c_end == -1) c_end = document.cookie.length;
      return unescape(document.cookie.substring(c_start, c_end));
    }
  }
  return "";
}

核心其實就是 document.cookie 這一句,其餘都是字串處理。要注意 document.cookie 回傳的是該網域下所有 cookie 的合併字串,看起來像這樣:

"username=amosli; ASPSESSIONID=GGIJNHCDK; __utma=119627022.98; __utmb=119627022.3"

因此流程是:先用 indexOf 找到目標名稱的位置,把索引往前推 c_name.length + 1 跳過名稱與等號,再從該位置往後找分號作為結尾。若找不到分號(代表它是最後一筆),就用整個字串的長度收尾。

使用 Cookie 完成歡迎訊息

function checkCookie() {
  var username = getCookie('username');
  if (username != null && username != "") {
    alert('歡迎回來 ' + username + '!');
  } else {
    username = prompt('請輸入您的名字:', "");
    if (username != null && username != "") {
      setCookie('username', username, 365);
    }
  }
}

完整範例

<html>
<head>
<script type="text/javascript">
function getCookie(c_name) {
  if (document.cookie.length > 0) {
    c_start = document.cookie.indexOf(c_name + "=");
    if (c_start != -1) {
      c_start = c_start + c_name.length + 1;
      c_end = document.cookie.indexOf(";", c_start);
      if (c_end == -1) c_end = document.cookie.length;
      return unescape(document.cookie.substring(c_start, c_end));
    }
  }
  return "";
}

function setCookie(c_name, value, expiredays) {
  var exdate = new Date();
  exdate.setDate(exdate.getDate() + expiredays);
  document.cookie = c_name + "=" + escape(value)
    + ((expiredays == null) ? "" : ";expires=" + exdate.toGMTString());
}

function checkCookie() {
  var username = getCookie('username');
  if (username != null && username != "") {
    alert('歡迎回來 ' + username + '!');
  } else {
    username = prompt('請輸入您的名字:', "");
    if (username != null && username != "") {
      setCookie('username', username, 365);
    }
  }
}
</script>
</head>

<body onLoad="checkCookie()">
</body>
</html>

幾個實務上的重要提醒

escape / unescape 已棄用。這兩個函式無法正確處理非 ASCII 字元,中文姓名會被編碼成乱码。應改用 encodeURIComponent() 與 decodeURIComponent():

document.cookie = c_name + "=" + encodeURIComponent(value) + ";expires=" + exdate.toUTCString();

同時 toGMTString() 也已棄用,改用 toUTCString()。

沒有指定 path 會造成困擾。Cookie 預設只屬於目前的路徑,同一網域下的其他目錄讀不到。通常應明確加上 ;path=/ 讓整個站台都能存取。

查詢時要留意名稱前綴。用 indexOf("username=") 搜尋時,若存在另一個名為 myusername 的 cookie,可能會誤中。嚴謹的做法是搜尋 "; " + c_name + "=" 並額外處理字串開頭的情況。

現代替代方案

若非必要,優先考慮 localStorage 與 sessionStorage。它們的 API 簡潔得多,容量更大(通常 5MB 起,cookie 只有約 4KB),且不會在每次請求時都被送到伺服器:

localStorage.setItem('username', 'amosli');   // 永久保存
sessionStorage.setItem('username', 'amosli'); // 關閉分頁即清除

var name = localStorage.getItem('username');  // 取回,不存在時為 null
localStorage.removeItem('username');          // 刪除
localStorage.clear();                         // 清空全部

選擇標準很簡單:需要伺服器自動讀到的(如工作階段識別碼)用 cookie;純粹前端要記住的偏好設定用 localStorage;只在單一分頁有效用 sessionStorage。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved