-2

how can I call code when I close page/window

alert("its close now");

but not onunload or onbeforeunload , cause this also call when refresh I want to call this alert when close only

4

2 回答 2

1

but not onunload or onbeforeunload , cause this also call when refresh I want to call this alert when close only

When you Refresh, the current page is essentially closed and re-opened causing the onunload and onbeforeunload events to fire. AFAIK, you can't avoid that when users refresh the page.

于 2012-06-03T18:53:22.883 回答
0

这是给您的注意事项:

Refresh = Closing window and reopening it

所以你将不得不使用onbeforeunload,因为不可能告诉用户已经刷新或关闭了窗口。

更新

根据您的评论:

我想知道用户何时打开页面以及何时关闭页面,以及在页面中停留的时间,与刷新页面的次数无关。

这可能是您所期望的:

localStorage["t"] || (localStorage["t"] = 0);
var start = new Date();
window.onbeforeunload = function(){
    localStorage["t"] = +localStorage["t"] + (new Date() - start);
}

用户停留在页面的时间存储在 中localStorage["t"],每次离开时都会更新。但是因为无法知道用户何时关闭了页面,所以你必须设置一个时间间隔。例如,将其重置为024 小时后。

于 2012-06-03T18:57:08.840 回答