Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any way to identify browser tab in JavaScript?

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?

like image 873
user1588877 Avatar asked Aug 10 '12 05:08

user1588877


People also ask

Can JavaScript access other tabs?

You can access the new window/tab if it was opened with JavaScript and the page indeed is in the same domain. var win = window. open("/path_to_page"); Then you'll have to wait for the page to load before you can access e.g. the title.

Is a browser a tab?

What's a Browser Tab? Browser tabs allow you to have multiple web pages at the same time, without juggling multiple windows on your desktop. Each open web page will appear as a “tab” at the top of your web browser window. You can click the tabs to switch between your open web pages.


2 Answers

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'; }); 
like image 176
M Rostami Avatar answered Oct 10 '22 03:10

M Rostami


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

like image 33
jmoreno Avatar answered Oct 10 '22 01:10

jmoreno