我發現有html事件window.onunload和window.onbeforeunload,但它們確實意味着文檔正在關閉/更改。似乎沒有一種通用的方式來檢測網絡瀏覽器關閉,這是一個驚喜。檢測Web瀏覽器關閉 - 可能的解決方案
我的應用程序可以在多個瀏覽器選項卡中工作,所以我有一個想法是創建一種參考計數器。這可能工作如下:
當用戶啓動我的web應用程序,在頁面onload處理程序我增加計數器並將值保存爲cookie。即++ pagecount並在cookie中保存值。
在window.onunload我遞減計數器(並保存cookie中的新值)。不確定是否有可能存在競爭條件儲存到cookie中?
當pagecount == 0我可以清理。
即使在我的web應用程序在多個瀏覽器中打開的情況下(但當然是相同的),這也可以工作。
我希望對此有任何評論?你認爲這是可行的嗎?可靠?任何我沒有預見到的問題?編輯: 下面是它如何工作的示例代碼。
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function SetCookie(c_name,value,exdays)
{
var exdate=new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
document.cookie=c_name + "=" + c_value + ";path=/";
}
function GetCookie(c_name)
{
var i,x,y,ARRcookies=document.cookie.split(";");
for (i=0;i<ARRcookies.length;i++)
{
x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
x=x.replace(/^\s+|\s+$/g,"");
if (x==c_name)
{
return unescape(y);
}
}
return "";
}
function bindEvent(el, eventName, eventHandler) {
if (el.addEventListener){
el.addEventListener(eventName, eventHandler, false);
} else if (el.attachEvent){
el.attachEvent('on'+eventName, eventHandler);
}
}
function IncrementUnload() {
var current = GetCookie("Unloaded") - 0;
++current;
SetCookie("Unloaded", current, 1);
//here you would compare Loaded and unloaded and if
//loaded == unloaded - then perform any cleanup
}
function printcookie() {
var here = document.getElementById("here");
if(here) {
here.innerHTML += " " + (GetCookie("Loaded") - 0);
}
}
function printunloadcookie() {
var there = document.getElementById("there");
if(there) {
there.innerHTML += " " + (GetCookie("Unloaded") - 0);
}
}
function init() {
var current = GetCookie("Loaded") - 0;
++current;
SetCookie("Loaded", current, 1);
bindEvent(window, "beforeunload", IncrementUnload);
}
window.onload = init;
</script>
</head>
<body>
<b>Close this window or press F5 to reload the page.</b>
<br /><br />
<p id="here">Loaded=</p>
<p id="there">Unloaded=</p>
<form>
<input type="button" id="print_cookie" value="print Loaded cookie" onclick="printcookie();">
<br />
<input type="button" id="print_unload_cookie" value="print Unloaded cookie" onclick="printunloadcookie();">
</form>
</body>
</html>
我認爲你可以使用localStorage的,而不是餅乾減少HTTP re任務開銷。通常你的方法沒有問題。 – Licson
localstorage在所有瀏覽器(尚未支持)上都不受支持 - 因此我偏好cookie。在任何情況下,一個(可能是單個數字)號碼的http開銷可能會很小。 –
本地存儲支持所有流行的瀏覽器(Chrome,Firefox,IE8 +,Opera和Safari),所以它不是問題。 – Licson