Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
318 views
in Technique[技术] by (71.8m points)

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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';
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...