简体   繁体   中英

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM