检测,如果两个浏览器窗口打开同一个网站
我试图来检测是否用户有我的网站在一个标签页中打开,然后在另一个选项卡中打开它。这应该然后显示一个警告,新开卡的用户。
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.
现在,我发送一个保持活动Ajax调用每秒回服务器。这则记录在一个唯一的ID数据库中的最后一个活动的时间。当一个新的页面被加载它会检查,如果用户(通过用户ID识别)是活跃在最后2秒之内。
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.
这感觉非常低效的。它也不能很好地执行,当用户刷新页面。 (这需要不到2秒)。我做了2秒钟的检查长于存活呼吁允许较慢的连接。
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)我要对这个正确的方式还是有这样做的更简单的方法?我听到的Gmail和Facebook可能会做同样的事情,但我无法找到该网站的功能中,他们做到这一点。
中国
实际code使用的内部功能很多所以这里的总体思路:
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:
伪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.
我已经尝试了一些解决方案的here但警告新的标签,而不是旧的人似乎是在压低延迟/时间方面的棘手的部分。
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.
您应该保持版本的内容中,首先在1,每个submited编辑它增加。 Submited编辑必须包括版本号,这是相对于当前和编辑被拒绝,如果他们不匹配。它也可能使AJAX调用请求的当前版本,并警告用户他的版本已经过时了。
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.
在SQL更新应该是这样的:
The sql update should look like this:
UPDATE table SET .... WHERE id = :id AND version = :version
然后检查受影响的行,如果是0,出现了一个concurent更新。你不会遇到竞争条件这样。
Then check affected rows, if it's 0, there was a concurent update. This way you won't encounter race condition.