Any way to identify browser tab in JavaScript?

浪子不回头ぞ 提交于 2019-11-27 01:07:37

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();

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:

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

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

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.

Some reference:

Get Browser Tab Index/Id

get urls of firefox tabs from firefox extension

How to differ sessions in browser-tabs?

Get a unique session in each browser tab

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

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.

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 localStorage to update current value for new tabs and in sessionStorage to fix page's 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 :-)

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

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

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.

Timestamp

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

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.

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

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!