Check if the browser tab is in focus in ReactJS

后端 未结 6 803
暗喜
暗喜 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:53

    Just built this using hooks as of React 16.8

    import React, { useEffect } from 'react';
    
    // User has switched back to the tab
    const onFocus = () => {
      console.log('Tab is in focus');
    };
    
    // User has switched away from the tab (AKA tab is hidden)
    const onBlur = () => {
      console.log('Tab is blurred');
    };
    
    const WindowFocusHandler = () => {
      useEffect(() => {
        window.addEventListener('focus', onFocus);
        window.addEventListener('blur', onBlur);
        // Specify how to clean up after this effect:
        return () => {
          window.removeEventListener('focus', onFocus);
          window.removeEventListener('blur', onBlur);
        };
      });
    
      return <>;
    };
    
    export default WindowFocusHandler;
    

提交回复
热议问题