我发现有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