检查我的网站是否在另一个选项卡中打开 [英] Check if my website is open in another tab

查看:23
本文介绍了检查我的网站是否在另一个选项卡中打开的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用 JavaScript 检查用户是否已经在浏览器的另一个标签中打开了我的网站.

I want to check with JavaScript if the user has already opened my website in another tab in their browser.

看来我不能用 pagevisibility...>

我看到的唯一方法是使用基于会话 cookie 的 WebSocket,并检查客户端是否有多个套接字.但是通过这种方式,从当前选项卡中,我必须询问我的服务器该用户是否在其当前浏览器选项卡旁边打开了一个选项卡.有点牵强!

It seems I cannot do that with pagevisibility...

也许使用 localstorage?

推荐答案

使用本地存储我创建了一个简单的演示,它应该可以完成您想要做的事情.基本上,它只是维护当前打开的窗口的计数.当窗口关闭时,卸载事件会触发并将其从总窗口计数中删除.

解决方案

当您第一次看到它时,您可能会认为发生的事情比实际情况要多.其中大部分是在谁是主要"角色中添加逻辑的一次大胆尝试.窗口,以及谁应该接任主要"关闭孩子时的窗口.(因此 setTimeout 调用重新检查是否应该将其提升到主窗口) 经过一番摸索之后,我认为实现它会花费太多时间并且超出了本问题的范围.但是,如果您打开了两个窗口(主窗口和子窗口)并且关闭了主窗口,则子窗口将被提升为主窗口.

Using local storage I created a simple demo that should accomplish what your looking to do. Basically, it simply maintains a count of currently opened windows. When the window is closed the unload events fire and remove it from the total window count.

在大多数情况下,您应该能够大致了解正在发生的事情并将其用于您自己的实施.

When you first look at it, you may think there's more going on than there really is. Most of it was a shotty attempt to add logic into who was the "main" window, and who should take over as the "main" window as you closed children. (Hence the setTimeout calls to recheck if it should be promoted to a main window) After some head scratching, I decided it would take too much time to implement and was outside the scope of this question. However, if you have two windows open (Main, and Child) and you close the Main, the child will be promoted to a main.

在此处查看所有操作:http://jsbin.com/mipanuro/1/edit

哦,是的,要实际看到它...在多个窗口中打开链接.:)

See it all in action here: http://jsbin.com/mipanuro/1/edit

我已经进行了必要的更改,以使本地存储维护主"存储.窗户.当您关闭选项卡时,子窗口可以提升为主窗口.有两种方法可以控制主"窗口状态通过传递给WindowStateManager 的构造函数的参数.这个实现比我之前的尝试要好得多.

Oh yeah, to actually see it in action... Open the link in multiple windows. :)

JavaScript:

JavaScript:

HTML:

HTML:

CSS:

#status
{
  display:table;
  width:100%;
  height:500px;
  border:1px solid black;
}
span
{
  vertical-align:middle;
  text-align:center; 
  margin:0 auto;
  font-size:50px;
  font-family:arial;
  color:#ba3fa3;  
  display:none;
}

#status.main .mainWindow,
#status.child .childWindow
{
  display:table-cell;
}

.mainWindow
{
  background-color:#22d86e;
}
.childWindow
{
  background-color:#70aeff;
}

这篇关于检查我的网站是否在另一个选项卡中打开的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆