Best way to detect when a user leaves a web page?

前端 未结 8 2158
太阳男子
太阳男子 2020-11-22 01:57

What is the best way to detect if a user leaves a web page?

The onunload JavaScript event doesn\'t work every time (the HTTP request takes longer than t

8条回答
  •  难免孤独
    2020-11-22 02:22

    I know this question has been answered, but in case you only want something to trigger when the actual BROWSER is closed, and not just when a pageload occurs, you can use this code:

    window.onbeforeunload = function (e) {
            if ((window.event.clientY < 0)) {
                //window.localStorage.clear();
                //alert("Y coords: " + window.event.clientY)
            }
    };
    

    In my example, I am clearing local storage and alerting the user with the mouses y coords, only when the browser is closed, this will be ignored on all page loads from within the program.

提交回复
热议问题