Check if the browser tab is in focus in ReactJS

后端 未结 6 791
暗喜
暗喜 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 05:06

    Found this library. It could be of help... https://www.npmjs.com/package/react-page-visibility Here's how I would use it to solve your problem

    import React from 'react;
    import PageVisibility from 'react-page-visibility';
    
    class YourComponent extends React.Component {
        state = {
          isWindowInFocus: true,
        }
        componentDidMount() {
          const { isWindowInFocus } = this.props;
          if (!isWindowInFocus) {
            // do something
          }
        }
    
        listentoWindow = isVisible => {
          this.setState({
            isWindowInFocus: isVisible,
          });
        }
        render() {
          return (
            
              
    Your component JSX
    ); } }

提交回复
热议问题