Javascript 可以检测用户是否打开了您网站的多个选项卡?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4038629/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Possible to detect if a user has multiple tabs of your site open?
提问by mpen
I'm just thinking about the whole site registration process.
我只是在考虑整个网站注册过程。
A user goes to your site, signs up, and then you tell him you've sent him an email and he needs to verify his email address. So he hits Ctrl+T, pops open a new tab, hits his Gmail
fav button, doesn't read a word of your lengthy welcome email, but clicks the first link he sees. Gmail opens your site in yet another tab...
用户访问您的网站,注册,然后您告诉他您已经向他发送了一封电子邮件,他需要验证他的电子邮件地址。所以他点击Ctrl+ T,弹出一个新标签,点击他的Gmail
收藏按钮,没有阅读你冗长的欢迎电子邮件,而是点击他看到的第一个链接。Gmail 在另一个标签页中打开您的网站...
He doesn't need nor want two tabs for your site open, he just wants to view that darn page you've disallowed him access to until he registers.
他不需要也不希望为您的网站打开两个选项卡,他只想查看您在注册之前不允许他访问的该死的页面。
So what do we do? I saw one site (but I forget what it was) that did a really good job, and it actually refreshed the first tab I had open without me having to press anything.
那么我们该怎么办?我看到一个网站(但我忘记了它是什么)做得非常好,它实际上刷新了我打开的第一个选项卡,而我无需按任何东西。
I'm thinking, it might be nice if we can detect if the user already has a tab to your site open, we could either close the new verification-tab automatically, or tell him he can close it can go back to his other tab (which we've now refreshed and logged him in).
我在想,如果我们能够检测到用户是否已经打开了您网站的选项卡,我们可以自动关闭新的验证选项卡,或者告诉他他可以关闭它可以返回到他的另一个选项卡,这可能会很好(我们现在已经刷新并让他登录了)。
Or, maybe when he got your annoying "please check your email" message, he went directly to his email, replacing your site with his email knowing full well that the email will link him back to the site again. In that case, we don't want to close the tab, but maybe could have saved his location from before, and redirect him there again?
或者,也许当他收到您烦人的“请检查您的电子邮件”消息时,他会直接转到他的电子邮件,用他的电子邮件替换您的网站,他完全知道该电子邮件会将他再次链接回该网站。在那种情况下,我们不想关闭选项卡,但也许可以从之前保存他的位置,然后再次将他重定向到那里?
Anyway, that's just the use case... the question still stands. Can we detect if a user already has a tab to your site open?
无论如何,这只是用例……问题仍然存在。我们可以检测用户是否已经打开了您网站的标签页吗?
This question is notabout how to detect whena user has completed the sign-up process. Ajax polling or comet can solve that issue. I specifically want to know if the user already has a tab open to your site or not.
这个问题不是关于如何检测用户何时完成了注册过程。Ajax 轮询或 Comet 可以解决这个问题。我特别想知道用户是否已经为您的网站打开了一个选项卡。
回答by 88ad
I'm fairly late to the party here (over a year), but I couldn't help but notice that you'd missed an incredibly easy and elegant solution (and probably what that website you saw used).
我参加聚会已经很晚了(一年多),但我忍不住注意到您错过了一个非常简单和优雅的解决方案(可能还有您看到的那个网站使用的)。
Using JavaScript you can change the name of the window you currently have open through:
使用 JavaScript,您可以更改当前打开的窗口的名称:
window.name = "myWindow";
Then when you send out your confirmation email simply do (assuming you're sending a HTML email):
然后,当您发送确认电子邮件时,只需执行以下操作(假设您发送的是 HTML 电子邮件):
<a href="verificationlink.php" target="myWindow">Verify</a>
Which should result in the verificationLink
opening up inside the window your website was already loaded into, if it's already been closed it'll open up a new tab with the window name specified.
这应该导致在verificationLink
您的网站已经加载到的窗口内打开,如果它已经关闭,它将打开一个指定窗口名称的新选项卡。
回答by SLaks
You can send an AJAX request every Xseconds from the original tab that asks the server if it received a request from the email.
您可以每X秒从原始选项卡发送一个 AJAX 请求,询问服务器是否收到来自电子邮件的请求。
You cannot close the second tab automatically, but you could have it ask the server after 3Xseconds whether it heard from the first tab.
您不能自动关闭第二个选项卡,但您可以让它在3X秒后询问服务器是否从第一个选项卡中听到。
回答by SLaks
You can stop the page functionality when user opened another tab or another window or even another browser
当用户打开另一个选项卡或另一个窗口甚至另一个浏览器时,您可以停止页面功能
$(window).blur(function(){
// code to stop functioning or close the page
});
回答by Anthony Vipond
What I have here is a little bit different use case to you but it detects if the site is being accessed in another tab. In this case I wanted to limit people using some call center pages to only one tab. It works well and is purely client-side.
我这里的用例与您略有不同,但它会检测是否正在另一个选项卡中访问该站点。在这种情况下,我想将使用某些呼叫中心页面的人限制为只有一个选项卡。它运行良好,纯粹是客户端。
// helper function to set cookies
function setCookie(cname, cvalue, seconds) {
var d = new Date();
d.setTime(d.getTime() + (seconds * 1000));
var expires = "expires="+ d.toUTCString();
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}
// helper function to get a cookie
function getCookie(cname) {
var name = cname + "=";
var decodedCookie = decodeURIComponent(document.cookie);
var ca = decodedCookie.split(';');
for(var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
// Do not allow multiple call center tabs
if (~window.location.hash.indexOf('#admin/callcenter')) {
$(window).on('beforeunload onbeforeunload', function(){
document.cookie = 'ic_window_id=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;';
});
function validateCallCenterTab() {
var win_id_cookie_duration = 10; // in seconds
if (!window.name) {
window.name = Math.random().toString();
}
if (!getCookie('ic_window_id') || window.name === getCookie('ic_window_id')) {
// This means they are using just one tab. Set/clobber the cookie to prolong the tab's validity.
setCookie('ic_window_id', window.name, win_id_cookie_duration);
} else if (getCookie('ic_window_id') !== window.name) {
// this means another browser tab is open, alert them to close the tabs until there is only one remaining
var message = 'You cannot have this website open in multiple tabs. ' +
'Please close them until there is only one remaining. Thanks!';
$('html').html(message);
clearInterval(callCenterInterval);
throw 'Multiple call center tabs error. Program terminating.';
}
}
callCenterInterval = setInterval(validateCallCenterTab, 3000);
}
回答by Neil VanLandingham
To flesh out John's answer, here is a working solution that uses plain JS and localStorage and updates the DOM with the count of the currently open tabs. Note that this solution detects the number of open tabs/windows for a given domain within one browser, but does not maintain the count across different browsers.
为了充实 John 的答案,这里有一个工作解决方案,它使用纯 JS 和 localStorage 并使用当前打开的选项卡的计数更新 DOM。请注意,此解决方案会检测一个浏览器中给定域的打开选项卡/窗口的数量,但不会维护不同浏览器之间的计数。
It uses the storage event to keep the count synchronized across all open tabs/windows without any need for refreshing the page.
它使用存储事件来保持所有打开的选项卡/窗口之间的计数同步,而无需刷新页面。
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title></title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="robots" content="noindex, nofollow">
<meta name="googlebot" content="noindex, nofollow">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script>
(function() {
var stor = window.localStorage;
window.addEventListener("load", function(e) {
var openTabs = stor.getItem("openTabs");
if (openTabs) {
openTabs++;
stor.setItem("openTabs", openTabs)
} else {
stor.setItem("openTabs", 1)
}
render();
})
window.addEventListener("unload", function(e) {
e.preventDefault();
var openTabs = stor.getItem("openTabs");
if (openTabs) {
openTabs--;
stor.setItem("openTabs", openTabs)
}
e.returnValue = '';
});
window.addEventListener('storage', function(e) {
render();
})
function render() {
var openTabs = stor.getItem("openTabs");
var tabnum = document.getElementById("tabnum");
var dname = document.getElementById("dname");
tabnum.textContent = openTabs;
dname.textContent = window.location.host
}
}());
</script>
</head>
<body>
<div style="width:100%;height:100%;text-align:center;">
<h1 >You Have<h1>
<h1 id="tabnum">0</h1>
<h1>Tab(s) of <span id="dname"></span> Open</h1>
</div>
</body>
</html>
回答by Shubanker
It is possible to track number of tabs of your site opened by saving data in localstorage
of each tab and counting the same, I created a github repositorywhich can track number of tabs of your website a user has opened.
通过在localstorage
每个选项卡中保存数据并计算相同的数量,可以跟踪您网站打开的选项卡数量,我创建了一个github 存储库,可以跟踪用户打开的网站选项卡数量。
To use it Include tab-counter.jsin your page and it will start tracking number of opened tabs.
使用它在您的页面中包含tab-counter.js,它将开始跟踪打开的标签的数量。
console.log(tabCount.tabsCount());
回答by spender
The user will still have a session at the server. Why not store the user's location prior to registration, and when they confirm their registration, read the location back out of the session and redirect back to that page. No tab magic required. It's certainly not what I'd expect from a signup process.
用户仍将在服务器上有一个会话。为什么不在注册之前存储用户的位置,当他们确认注册时,从会话中读取位置并重定向回该页面。不需要制表符魔术。这当然不是我对注册过程的期望。
回答by John
To add to other answers: You can also use localStorage. Have an entry like 'openedTabs'. When your page is opened, increase this number. When user leaves the page, decrease it.
添加到其他答案:您还可以使用 localStorage。有一个像“openedTabs”这样的条目。当您的页面打开时,增加此数字。当用户离开页面时,减少它。