I'm trying to detect if user has my website open in one tab, then opens it in another tab. This should then show a warning to the user on the newly opened tab.
Right now I'm sending a "keep alive" ajax call every second back to the server. This then logs the "last active" time in the database with a unique ID. When a new page is loaded it checks if that user (identified by a userID) was active within the last 2 seconds.
This feels very inefficient. It also doesn't perform well when the user refreshes the page. (which takes less than 2 seconds). I've made the 2 second check longer than the keepalive call to allow for slower connections.
Q) Am I going about this the right way or is there an easier way of doing this? I heard Gmail and Facebook might do something similar but I can't find the site function in which they do it.
Actual code uses lots of in-house functions so here's the general idea:
Pseudo code:
Page load;
[index] PHP: Save tabsessionid, userid, datecreated, lastactive, phpsessionid into database;
[index] JS: Every second, send tabsessionid to keepalive.php
[keepalive] PHP: Check if another session exists in the last 2 seconds
[keepalive] PHP: If exists -> Return "-1"; else -> return "1";
[keepalive] PHP: Update tabsessionid's last active time.
I've tried some of the solutions here but warning the newer tab, not the older one seems to be the tricky part in terms of keeping down latency/time.
You should keep version of the content, initially at 1, with each submited edit it increases. Submited edits must include version number, which is compared to the current one and the edit is refused if they don't match. It's also possible to make ajax calls to ask for the current version, and warn the user his version is outdated.
The sql update should look like this:
UPDATE table SET .... WHERE id = :id AND version = :version
Then check affected rows, if it's 0, there was a concurent update. This way you won't encounter race condition.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With