Home » Php » Any way to check if someone has closed their browser using Javascript/PHP?

Any way to check if someone has closed their browser using Javascript/PHP?

Posted by: admin July 12, 2020 Leave a comment

Questions:

I’m working on a PHP/MySQL/Javascript based online chess game. One problem I’ve encountered is the possibility of a user on one end just closing his browser. Is there any way to reliably detect if someone has been idle/closed the page?

As an added complication, our school server does not support cron jobs -_-

How to&Answers:

The only reliable way to do this is to use a pinging technique to your server, as the other commenters have suggested. This way you control the game, not the browsers. The way you’d have to “track” users is to fire an AJAX call…I think every 5 seconds is often enough…to the server. All this will do is either INSERT something into a “tracking” table or UPDATE a new column you make in your “Games” table to keep track of the last time the user had server activity (ignoring normal moves in the game…you can do this same process for normal moves and reset the interval of pinging as well, to avoid excessive checking). So every time a user makes a move (or something else that requires a server interaction), you would have to make a check for the time of their opponent’s last server activity – if the opponent hasn’t made a move within 7 seconds of the current time, then the opponent’s browser has stopped communicating (for whatever reason). The reason I say 7 seconds is because of extra processing that takes place for server/database communications and any possible network lagging. Since network lagging is probably the bottleneck, you might want to increase this value to something like 10.

Answer:

You can’t with exact certainty know whether the client is closed. You can make some qualified guesses, but it will never be reliable.

Maybe you could find a comprise where you are satisfied with knowing if a client session is active or not?

A low-tech solution would be to save the session id (or a selfmade unique identifying string) along with a timestamp.
Whenever the client makes a new request (new page load and/or with AJAX), update the timestamp.

Since you don’t have access to cronjobs, you need to make another compromise – let the other visitors tell you whether the client still is active.
Whenever a visitor loads a page, run through the table which stores the session id’s and timestamps and see if any sessions looks older than what you would consider being active.

It’s not a sulotion to your exact problem (since it cannot be done) but a low-tech compromise.

Answer:

You can simply set a ‘RECURSIVE’ ajax script on that page and that script silently send updated time to the server after small time period. And on the server you have to write that Request Listener Script to log this details. If you see that a users request is stopped or it is not coming for last some times, then he closed his browser.