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.