[HTML 5] Page Visibility API

const initPageVisibility = () => {
  setInterval(() => console.log(document.visibilityState), 1000)
}

if ('visibilityState' in document) {
    initPageVisibility()
}

 If you click other tab, the current tab should be in `hidden` state, otherwise will be in `visible` state.

 

visibilitychange event 

const initPageVisibility = () => {
  const handleVisibilityChange = () => {
      console.log(e.target.visibilityState); // the same
      console.log(document.visibilityState); // the same
      
      const {visibilityState} = e.target;
      
      switch(visibilityState) {
          case 'hidden': {
              console.log('document is hidden!')
              break;
          }
          case 'visibile': {
              console.log('document is visible!')
              break;
          }
      }
  }
  document.addEventListener('visibilitychange', handleVisibilityChange);
}

if ('visibilityState' in document) {
    initPageVisibility()
}

 

posted @ 2022-06-24 19:15  Zhentiw  阅读(27)  评论(0编辑  收藏  举报