使用者直接關閉瀏覽器視窗 (點 ×、Alt+F4、右鍵關閉) 時,伺服器無法立即得知,Session 只能等逾時過期。需在關閉瞬間發送請求清除 Session。
IE 關閉視窗時,window.screenLeft 與 window.screenTop 會變成極大值 (約 10000+)。結合 event.altKey (Alt+F4) 可判斷使用者主動關閉視窗,而非重新整理、跳轉等正常導航。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Session 清除測試</title>
</head>
<body>
<h1>測試頁面 - 請嘗試關閉視窗</h1>
<p>開啟開發者工具 Network 面板觀察請求</p>
<script>
// 延遲函數 (同步阻塞,確保請求發出)
function sleep(ms) {
var start = new Date().getTime();
while (new Date().getTime() - start < ms) { /* busy wait */ }
}
window.onunload = function(e) {
e = e || window.event;
// 判斷是否為使用者主動關閉視窗
// screenLeft/Top >= 10000 表示視窗已移出螢幕 (關閉過程中)
// event.altKey 捕捉 Alt+F4
var isClosing = (window.screenLeft >= 10000 && window.screenTop >= 10000) || e.altKey;
if (isClosing) {
console.log('偵測到關閉視窗,screenLeft:', window.screenLeft, 'screenTop:', window.screenTop);
// 方法:開啟極小視窗發送請求,再關閉它
// 必須同步等待,否則瀏覽器會中斷請求
var clearWin = window.open('ClearSession.ashx', '_blank',
'width=1,height=1,left=-1000,top=-1000,toolbar=no,menubar=no,location=no,status=no');
if (clearWin) {
clearWin.opener = null; // 斷開關係
sleep(2000); // 等待 2 秒確保請求完成 (同步阻塞)
clearWin.close();
}
}
};
</script>
</body>
</html>
using System;
using System.Web;
using System.Web.SessionState;
public class ClearSession : IHttpHandler, IRequiresSessionState
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
// 清除 Session
context.Session.Abandon(); // 立即終止 Session
context.Session.Clear(); // 清除所有 Session 變數
context.Session.RemoveAll(); // 別名
// 可選:清除 Session Cookie
if (context.Request.Cookies["ASP.NET_SessionId"] != null) {
var cookie = new HttpCookie("ASP.NET_SessionId") {
Expires = DateTime.Now.AddDays(-1),
Path = "/"
};
context.Response.Cookies.Add(cookie);
}
context.Response.Write("Session cleared at " + DateTime.Now);
}
public bool IsReusable { get { return false; } }
}
onbeforeunload:頁面卸載前,可取消 (返回字串)。可用 window.location 導向/發送請求。onunload:頁面正在卸載,**不可取消**,window.location 無效 (瀏覽器已中斷導航)。必須用 window.open 新視窗發送請求。width=1,height=1,left=-1000,top=-1000 讓視窗不可見,不干擾使用者。screenLeft >= 10000 條件可有效過濾 F5 重新整理、連結跳轉等正常導航 (此時座標正常)。fetch('/keepalive'),後端更新 Session 存活時間。若連續 N 次無心跳,視為離線清除 Session。window.addEventListener('beforeunload', function() {
navigator.sendBeacon('/ClearSession.ashx'); // 非同步、可靠、不阻塞
});
sessionState timeout="20" (分鐘),不依賴前端通知。IE 時代的 screenLeft >= 10000 + window.open 同步請求是經典但脆弱的方案 (僅限 IE、易被攔截、體驗差)。現代專案應採用 **心跳機制 + 伺服端逾時** 為主,輔以 navigator.sendBeacon 於 beforeunload 發送清除請求,徹底拋棄 onunload 同步阻塞寫法。