DIV CSS 佈局教程網

用 Cookie 讓同一頁面只能開啟一次
編輯:關於JavaScript     

做 WebIM 嵌進 OA 系統時遇到一個實際問題:IM 在獨立頁面,使用者連點幾下就會開好幾個視窗,而 IE6 下伺服器推送會認錯頁面。解法是用 Cookie 做一個「頁面是否已開」的旗標。

實作程式碼

<script language="javascript" type="text/javascript">
window.onload = function () {
  if (GetCookie("IsOpen") == "") {
    SetCookie("IsOpen", "1");
    StartService();
  } else {
    window.onunload = null;
    window.opener = null;
    window.open("", "_self");
    window.close();
  }
}

window.onunload = function () {
  if (GetCookie("IsOpen") != "")
    DeleteCookie("IsOpen");
}

function GetCookieVal(offset) {
  /// 取得名稱為 offset 的 cookie 值
  var endstr = document.cookie.indexOf(";", offset);
  if (endstr == -1)
    endstr = document.cookie.length;
  return unescape(document.cookie.substring(offset, endstr));
}

function GetCookie(name) {
  /// 根據名稱獲得 Cookie 值
  var arg = name + "=";
  var alen = arg.length;
  var clen = document.cookie.length;
  var i = 0;
  while (i < clen) {
    var j = i + alen;
    if (document.cookie.substring(i, j) == arg)
      return GetCookieVal(j);
    i = document.cookie.indexOf(" ", i) + 1;
    if (i == 0) break;
  }
  return "";
}

function SetCookie(name, value) {
  /// 設置 Cookie
  var argc = SetCookie.arguments.length;
  var argv = SetCookie.arguments;
  var path   = (argc > 3) ? argv[3] : null;
  var domain = (argc > 4) ? argv[4] : null;
  var secure = (argc > 5) ? argv[5] : false;
  document.cookie = name + "=" + value +
    ((path == null) ? "" : ("; path=" + path)) +
    ((domain == null) ? "" : ("; domain=" + domain)) +
    ((secure == true) ? "; secure" : "");
}

function DeleteCookie(name) {
  /// 刪除 Cookie:把過期時間設為過去
  var exp = new Date();
  exp.setTime(exp.getTime() - 1);
  var cval = GetCookie(name);
  document.cookie = name + "=" + cval + "; expires=" + exp.toGMTString();
}
</script>

把這段放到 head 裡就可以了。邏輯是這樣的:頁面載入時檢查 IsOpen,沒值代表這是首開,寫入旗標並啟動服務;有值代表已經開過,就把這個新視窗關掉。頁面卸載時刪除旗標,下次開啟又會被視為首次。

如果是 window.open 開的頁面,更簡單

var win = null;   // 定義一個變量去判斷就可以了
if (win == null)
{
  win = window.open("Main.aspx", '', strfeatures);
}

用一個變數記住視窗參照,就不必動用 Cookie。但這個方法有前提:變數必須存在於同一個 window 環境。如果開啟的動作可能來自不同頁面或 iframe,變數就各自為政,這時 Cookie 或 localStorage 才是跨頁共享的可靠選擇。

幾個實務上的坑

第一,window.onunload 並不總是可靠——瀏覽器當機、程序被強制結束、使用者直接關閉分頁,旗標都可能沒被清掉,於是所有人都開不了頁面。比較穩健的做法是搭配 sessionStorage(分頁級隔離)或用 BroadcastChannel/localStorage 做跨分頁廣播,由伺服器端以連線狀態為準。

第二,那幾行 window.opener = null、window.open("", "_self")、window.close() 是為了讓腳本開的視窗能自我了結;一般使用者手動開的分頁,window.close() 會被瀏覽器阻擋,這是刻意的安全設計,不要繞過它。

第三,Cookie 的旗標值只是「有/沒有」,別拿它當身分或權限依據,那類資料一律以伺服器為準。

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