有什么方法可以在 JavaScript 中识别浏览器选项卡?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11896160/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 07:35:22  来源:igfitidea点击:

Any way to identify browser tab in JavaScript?

javascriptbrowsertabsuniqueidentifier

提问by user1588877

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.

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

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).

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

Any ideas?

有任何想法吗?

回答by M Rostami

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

SessionStorage 是每个选项卡/窗口,因此您可以在 sessionStorage 中定义一个随机数,如果存在,首先获取它:

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

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

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

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

回答by jmoreno

You have to be using html5, but sessionStoragecombined with a random guid would seem to be what you want.

您必须使用 html5,但sessionStorage与随机 guid 相结合似乎是您想要的。

回答by schlebe

Since I don't have find no simple Javascript function as windows.currentTabIndex, I have written some lines of Javascript to fix an ID on each browser tabs when they are loaded.

由于我没有找到简单的 Javascript 函数windows.currentTabIndex,所以我编写了一些 Javascript 行来在加载每个浏览器选项卡时修复它们上的 ID。

function defineTabID()
    {
    var iPageTabID = sessionStorage.getItem("tabID");
      // if it is the first time that this page is loaded
    if (iPageTabID == null)
        {
        var iLocalTabID = localStorage.getItem("tabID");
          // if tabID is not yet defined in localStorage it is initialized to 1
          // else tabId counter is increment by 1
        var iPageTabID = (iLocalTabID == null) ? 1 : Number(iLocalTabID) + 1;
          // new computed value are saved in localStorage and in sessionStorage
        localStorage.setItem("tabID",iPageTabID);
        sessionStorage.setItem("tabID",iPageTabID);
        }
    }

This code save last tab's index in localStorageto update current value for new tabs and in sessionStorageto fix page's id !

此代码保存最后一个选项卡的索引localStorage以更新新选项卡的当前值并sessionStorage修复页面的 id !

I must call defineTabId()function in each pages of my application. Since I develop using a JSF templates, this is only defined in only one place :-)

我必须defineTabId()在应用程序的每个页面中调用函数。由于我使用 JSF 模板进行开发,因此仅在一个地方定义了 :-)

回答by Trinh Hoang Nhu

You can not get tab id with javascript, how ever there is some solution that can help you with like using different session / cookies when user open new tab.

您无法使用 javascript 获取标签 ID,但是有一些解决方案可以帮助您在用户打开新标签时使用不同的会话/cookie。

Some reference:

一些参考:

Get Browser Tab Index/Id

获取浏览器标签索引/ID

get urls of firefox tabs from firefox extension

从 Firefox 扩展中获取 Firefox 标签的 URL

How to differ sessions in browser-tabs?

如何在浏览器选项卡中区分会话?

Get a unique session in each browser tab

在每个浏览器选项卡中获取唯一会话

asp.net - session - multiple browser tabs - different sessions?

asp.net - 会话 - 多个浏览器选项卡 - 不同的会话?

回答by DioNNiS

One of the possible solutions is using "window.name" property, but I do not want to use it because somebody else can use it.

一种可能的解决方案是使用“window.name”属性,但我不想使用它,因为其他人可以使用它。

I found one more possible solution: using sessionStorage. It supported by FF3.5+, Chrome4+, Safari4+, Opera10.5+, and IE8+.

我找到了另一种可能的解决方案:使用 sessionStorage。FF3.5+、Chrome4+、Safari4+、Opera10.5+、IE8+支持。

回答by eaglei22

If there isn't any odds of a user opening 3 tabs within 2 milliseconds, could use a timestamp and store that into window.name and use that as the key in your lookup. The window.name value will stay with the tab until it is closed.

如果用户在 2 毫秒内打开 3 个选项卡的可能性不大,则可以使用时间戳并将其存储到 window.name 中,并将其用作查找中的键。window.name 值将保留在选项卡中,直到它关闭。

Timestamp

时间戳

回答by Matt Wills

For anyone on here using React, I made a sneaky little hook:

对于这里使用 React 的任何人,我做了一个偷偷摸摸的小钩子:

import {useEffect, useMemo} from 'react'
import uniqid from 'uniqid'

export const TAB_ID_KEY = 'tabId'

export default () => {
  const id = useMemo(uniqid, [])

  useEffect(() => {
    if (typeof Storage !== 'undefined') {
      sessionStorage.setItem(TAB_ID_KEY, id)
    }
  }, [id])

  return id
}

Put this on your base App/Page component, or somewhere that you know will always be mounted.

将它放在您的基本应用程序/页面组件上,或者您知道将始终安装的某个地方。

It'll run the effect after mounting and set a unique id for the current tab in session storage, which is storage specific to the tab.

它会在挂载后运行效果,并为会话存储中的当前选项卡设置一个唯一的 id,这是特定于选项卡的存储。

Duplicating the tab will get you a new id for the new tab, since the component will mount again and the effect will run, overwriting the previous tab's id

复制选项卡将为您提供新选项卡的新 id,因为组件将再次安装并且效果将运行,覆盖前一个选项卡的 id

回答by AlikElzin-kilaka

Here's a way to have the tabIdavailable after the page was loaded - having the same tabIdeven after refresh.

这是一种tabId在页面加载后可用的方法-tabId即使在刷新后也保持相同。

This also solves the issue of duplicate tabs, as the tabIdis cleared from the sessionStorage.

这也解决了重复的标签的问题,因为tabId从清除sessionStorage

window.addEventListener("beforeunload", function (e)
{
    window.sessionStorage.tabId = window.tabId;

    return null;
});

window.addEventListener("load", function (e)
{
    if (window.sessionStorage.tabId)
    {
        window.tabId = window.sessionStorage.tabId;
        window.sessionStorage.removeItem("tabId");
    }
    else
    {
        window.tabId = Math.floor(Math.random() * 1000000);
    }

    return null;
});

Access the tabIdusing window.tabId.

访问tabId使用window.tabId.

The beforeunloadevent is needed in order to persist the tabIdto have the same id available after refresh.

beforeunload需要该事件以保持tabId刷新后具有相同的可用 id。

The loadevent is needed to:

load事件需要:

  1. Generate the initial tabId.
  2. Load the same tabIdafter refresh - if exists.
  1. 生成初始tabId.
  2. tabId刷新后加载相同的内容- 如果存在。

* I don't really know why I should do return nullor return at all. Just read that not returning may cause the function to not work :(

* 我真的不知道为什么我应该做return null或返回。只是读到不返回可能会导致函数不起作用:(

回答by Ofek Shilon

At least for chrome, there's an official answer since 2013: chrome.tabs API.

至少对于 chrome,自 2013 年以来就有一个官方答案: chrome.tabs API