有什么方法可以在 JavaScript 中识别浏览器选项卡? [英] Any way to identify browser tab in JavaScript?

查看:33
本文介绍了有什么方法可以在 JavaScript 中识别浏览器选项卡?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要能够在浏览器中识别我所在的选项卡.难道我不能从浏览器中获取一些信息来识别选项卡吗?我不需要知道任何其他选项卡的任何信息,我只需要我所在选项卡的 id.它可以是随机数或序列号,或者日期时间戳,只要它保持不变标签的寿命.

I need to be able to identify what tab I am in within the browser. Isn't there some bit of information I can get from the browser to identify the tab? I don't need to know anything about any other tabs, I just need an id for the tab I am in. It could be a random or sequenced number, or a date-time stamp, as long as it remains the same for the life of the tab.

我有一个客户端应用程序,它通过 HTTP 连接到远程服务器,如果我在多个选项卡中打开它,每个实例都需要自己的唯一 ID 或应用程序失败,所以我只需要一些唯一的数字只要该选项卡存在,就与该选项卡相关联(即,当我浏览提供此应用程序的站点时,页面刷新后仍然存在的内容).看起来很简单,应该只在浏览器中可用,比如 window.tabId - 这就是我所需要的.我有一个严重的开发障碍,因为我无法通过这个似乎不存在的简单、简单、简单的解决方案.一定有办法(跨浏览器解决方案).

I have a client side app that makes a BOSH over HTTP connection to a remote server, and if I open it in multiple tabs, each instance needs its own unique id or the app fails, so I just need some unique number that is associated with the tab for as long as that tab exists (i.e. something that survives page refresh as I navigate the site that provides this app). Seems like a no-brainer that should just be available in the browser, like window.tabId - that's all I need. I've got a serious development block because I cannot get past this simple, simple, simple solution that doesn't seem to exist. There must be a way (a cross-browser solution at that).

有什么想法吗?

推荐答案

SessionStorage 是针对每个 tab/window 的,所以你可以在 sessionStorage 中定义一个随机数,如果存在则首先获取它:

SessionStorage is per tab/window, so you can define a random number in sessionStorage and get it at first if exists:

var tabID = sessionStorage.tabID ? 
            sessionStorage.tabID : 
            sessionStorage.tabID = Math.random();

更新:
在某些情况下,您可能在多个选项卡中拥有相同的 sessionStorage(例如,当您复制选项卡时).在这种情况下,以下代码可能会有所帮助:

UPDATE:
In some cases, you may have same sessionStorage in multiple tab (e.g. when you duplicate tab). In that case, following code may help:

var tabID = sessionStorage.tabID && 
            sessionStorage.closedLastTab !== '2' ? 
            sessionStorage.tabID : 
            sessionStorage.tabID = Math.random();
sessionStorage.closedLastTab = '2';
$(window).on('unload beforeunload', function() {
      sessionStorage.closedLastTab = '1';
});

这篇关于有什么方法可以在 JavaScript 中识别浏览器选项卡?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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