Any way to identify browser tab in JavaScript?

后端 未结 9 558
孤独总比滥情好
孤独总比滥情好 2020-11-27 05:17

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 kn

相关标签:
9条回答
  • 2020-11-27 05:52

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

    0 讨论(0)
  • 2020-11-27 05:52

    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

    0 讨论(0)
  • 2020-11-27 06:04

    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';
    });
    
    0 讨论(0)
提交回复
热议问题