Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect if two browser windows are open to the same site

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.

like image 775
Jamie Taylor Avatar asked Oct 11 '13 07:10

Jamie Taylor


1 Answers

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.

like image 176
Marek Avatar answered Oct 01 '22 14:10

Marek