How to check users leave the page

I would like to know that the user is leaving the web page. I think there can be three scenarios: 1. go to another page on the same website, or open a new window, or load a new page in the current window, 2. go to a page on another site and 3. close the window.

Based on these scenarios, I think I need to check if the current window is the focus. So my first question is: is this correct? And the second question: how do I implement it in javascript?

0
source share
3 answers

See Mastering the Back Button with Javascript (this is the same principle). There are two relevant events: unloading and reloading. Also see the best way to detect when a user leaves a web page .

+4
source

I just want to comment that there is probably no reliable, cross-browser solution for this ... I know this does not attach much importance to your question, but if you can solve your problem in any other way, I think it will be also more ergonomic.

+1
source

, onunload.

jQuery(window).bind("unload", function() {
    //your code here
}); 

This should work when you click on the link, close the tab / window or click the "Back" button.

0
source

Source: https://habr.com/ru/post/1723774/


All Articles