Any way to identify browser tab in JavaScript?
JavascriptBrowserTabsUniqueidentifierJavascript Problem Overview
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.
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).
Any ideas?
Javascript Solutions
Solution 1 - Javascript
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 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';
});
Solution 2 - Javascript
You have to be using html5, but sessionStorage combined with a random guid would seem to be what you want.
Solution 3 - Javascript
Here's a way to have the tabId
available after the page was loaded - having the same tabId
even after refresh.
This also solves the issue of duplicate tabs, as the tabId
is cleared from the 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 tabId
using window.tabId
.
The beforeunload
event is needed in order to persist the tabId
to have the same id available after refresh.
The load
event is needed to:
- Generate the initial
tabId
. - Load the same
tabId
after refresh - if exists.
* I don't really know why I should do return null
or return at all. Just read that not returning may cause the function to not work :(
Solution 4 - Javascript
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 :-)
Solution 5 - Javascript
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:
https://stackoverflow.com/questions/4510454/get-browser-tab-index-id
https://stackoverflow.com/questions/1028630/get-urls-of-firefox-tabs-from-firefox-extension
https://stackoverflow.com/questions/368653/how-to-differ-sessions-in-browser-tabs
Get a unique session in each browser tab
https://stackoverflow.com/questions/2840615/asp-net-session-multiple-browser-tabs-different-sessions
Solution 6 - Javascript
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
Solution 7 - Javascript
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+.
Solution 8 - Javascript
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.
Solution 9 - Javascript
You can get the tab ID (or clientId) in "fetch" event handler of your service worker. If you need to send that clientId to your page, just use client.postMessage().
In your service worker:
self.addEventListener("fetch", function(event) {
event.waitUntil(async function() {
if (!event.clientId) return;
const client = await clients.get(event.clientId);
if (!client) return;
client.postMessage({
clientId: event.clientId,
});
}());
});
In your page script:
navigator.serviceWorker.addEventListener('message', event => {
console.log(event.data.clientId);
});
Sources: Client.postMessage()
Solution 10 - Javascript
At least for chrome, there's an official answer since 2013: chrome.tabs API.