简体   繁体   English

关闭页面/窗口时发出警报

[英]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.但不是onunloadonbeforeunload ,因为刷新时也会调用我想仅在关闭时调用此警报。

but not onunload or onbeforeunload , cause this also call when refresh I want to call this alert when close only但不是 onunload 或 onbeforeunload ,导致刷新时也会调用我只想在关闭时调用此警报

When you Refresh, the current page is essentially closed and re-opened causing the onunload and onbeforeunload events to fire.当您刷新时,当前页面实质上是关闭并重新打开,导致onunloadonbeforeunload事件触发。 AFAIK, you can't avoid that when users refresh the page. AFAIK,当用户刷新页面时,您无法避免这种情况。

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.所以你将不得不使用onbeforeunload ,因为它不可能告诉用户已经刷新或关闭了窗口。

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.用户停留在页面的时间存储在localStorage["t"]中,每次离开时都会更新。 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.例如,在 24 小时后将其重置为0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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