Any way to identify browser tab in JavaScript?

后端 未结 9 632
孤独总比滥情好
孤独总比滥情好 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:41

    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

提交回复
热议问题