DIV CSS 佈局教程網

用 Cookie 判斷頁面是否為首次打開
編輯:關於JavaScript     

有些功能需要區分「首次進入」和「刷新」,比如首次訪問的引導動畫、新手提示。用 Cookie 記錄一個標記位是最輕量的做法。下面先封裝一個可複用的 Cookie 類,再給出調用示例。

一、Cookie 類封裝

function Cookie(key, value) {
  this.key = key;
  if (value != null) {
    this.value = escape(value);
  }
  this.expiresTime = null;
  this.domain = null;
  this.path = "/";
  this.secure = null;
}

Cookie.prototype.setValue = function (value) { this.value = escape(value); };
Cookie.prototype.getValue = function () { return this.value; };
Cookie.prototype.setExpiresTime = function (time) { this.expiresTime = time; };
Cookie.prototype.getExpiresTime = function () { return this.expiresTime; };
Cookie.prototype.setDomain = function (domain) { this.domain = domain; };
Cookie.prototype.getDomain = function () { return this.domain; };
Cookie.prototype.setPath = function (path) { this.path = path; };
Cookie.prototype.getPath = function () { return this.path; };

Cookie.prototype.Write = function (v) {
  if (v != null) { this.setValue(v); }
  var ck = this.key + "=" + this.value;

  if (this.expiresTime != null) {
    try {
      ck += ";expires=" + this.expiresTime.toUTCString();
    } catch (err) {
      alert("expiresTime 參數錯誤");
    }
  }
  if (this.domain != null) { ck += ";domain=" + this.domain; }
  if (this.path != null) { ck += ";path=" + this.path; }
  if (this.secure != null) { ck += ";secure"; }

  document.cookie = ck;
};

Cookie.prototype.Read = function () {
  try {
    var cks = document.cookie.split("; ");
    for (var i = 0; i < cks.length; i++) {
      var fields = cks[i].split("=");
      if (fields[0] == this.key) {
        this.value = fields[1];
        return this.value;
      }
    }
    return null;
  } catch (err) {
    alert("cookie 讀取錯誤");
    return null;
  }
};

二、頁面中的調用方式

<script type="text/javascript" src="Cookie.js"></script>
<script type="text/javascript" language="javascript">
window.onload = function () {
  var ck = new Cookie("HasLoaded");
  // 每個頁面的 Cookie 名不要相同,否則會互相干擾

  if (ck.Read() == null) {
    // 未加載過,Cookie 內容為空
    alert("首次打開頁面");

    // 設置保存時間為一年
    var dd = new Date();
    dd = new Date(dd.getYear() + 1900, dd.getMonth(), dd.getDate());
    dd.setDate(dd.getDate() + 365);

    ck.setExpiresTime(dd);
    ck.Write("true");
  } else {
    // Cookie 存在,說明是刷新或再次打開
    alert("頁面刷新");
  }
};
</script>

三、幾點實踐提醒

第一,Cookie 名必須按頁面區分。多個頁面都用 HasLoaded,會導致只有第一個訪問過的頁面被標記。

第二,escape/unescape 已不推薦使用,處理中文時容易出亂碼,建議換成 encodeURIComponent/decodeURIComponent。

第三,document.cookie 讀取的是「所有匹配的 cookie 拼接串」,用 split("=") 解析時,若值本身含有 = 會被截斷,更穩妥的做法是只按第一個等號切分。

第四,若只是想在當前會話內判斷,用 sessionStorage 更合適;若需要持久化的本地狀態,localStorage 容量更大、API 也更友好。Cookie 每次請求都會隨 HTTP 頭發送,不適合存放大量數據。

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