简体   繁体   中英

How to detect when a user leaves your site excluding reload

I want to trigger an ajax call whenever the user leaves my site via closing the browser, closing the tab, or just switching to a new web site. However, I want to exclude reloads. I have seen solution like this on Atack Overflow:

window.onbeforeunload = function(){
  // call some ajax call
};

However this solution triggers on reload as well which is what I don't want.

Short answer: You can't, but you can achieve something close.

Have your server 'hold' the AJAX call for a few seconds, and add a JS snippet to the very top of your body that makes another AJAX request saying "I visited this page"

If the same cookie / session calls the "I visited this page" within a few seconds if leaving, then you know the user probably reloaded.

It's not foolproof, but it may be suitable for your needs.

You simply cannot guarantee that an ajax call will be successfully sent in every way that a browser window can be closed. You can try and may be successful some times, but it would be much better to find a better design that does not rely on that type of ajax call.

Further, a given browser window does not know when a reload is happening and when the user has just navigated to a new page. The old page and the new page are entirely different Javascript contexts which know nothing about each other.

One possible mechanism can be implemented mostly server-side and involves webSockets. Your page makes a webSocket connection to your server every time it loads. Whenever the page is closed the webSocket connection will also be closed.

The server can monitor the webSocket close to see every time a page is closed. If the server sets a short timer upon each webSocket close and each page has a cookie that identifies the user, then the server can see if the webSocket connection is re-established within a few seconds or not. If it is re-established, then the user was just doing a reload. If it is not re-established in that short time, then the user has closed or navigated away.

Using this mechanism, your server can monitor exactly when the user starts viewing the page and when the page is closed. And, if there is a very short interval between close and then open again, that is essentially a reload (which can be ignored). So, using this mechanism, you can track all client viewing of the web page.

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