Check if the browser tab is in focus in ReactJS

后端 未结 6 794
暗喜
暗喜 2021-02-07 04:20

I have a website in ReactJS. I want to get a callback whenever my tab comes in focus or is hidden. I came across the Page Visibility API for this but I\'m not able to figure out

6条回答
  •  孤独总比滥情好
    2021-02-07 04:57

    This should work:

    componentDidMount() {
        window.addEventListener("focus", this.onFocus)
    }
    
    componentWillUnmount() {
        window.removeEventListener("focus", this.onFocus)
    }
    
    onFocus = () => {
        //
    }
    

    Edit: same goes for "blur" and it should work for when the tab becomes hidden.

    Check @Assaf's answer for usage with hooks.

提交回复
热议问题