'Alert when close page/window

How can I call code when I close page/window

alert("its close now");

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



Solution 1:[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.

Solution 2:[2]

Here is a note for you:

Refresh = Closing window and reopening it

So you will have to use onbeforeunload, because it is impossible to tell the user has refreshed or closed the window.

UPDATE

Based on your comment:

I want to know when user open the page and when close it, and how long stay in the page, its not matter how many times refresh the page.

This might be what you expected:

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

The time the user stayed in the page is stored in localStorage["t"], and updated every time he leaves. But because it is impossible to tell when the user closed the page, so you will have to set up a time interval. For example, reset it to 0 after 24 hours.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Sarfraz
Solution 2