JS listens to events triggered by browser closing, refreshing, and switching tabs

It's a pretty simple thing. If you know it, you can do it. If you don't know it, you can't do it. There is no logic at all. Just record it briefly, just to deepen my impression.

visibilitychange

visibilitychange can monitor the browser's switching tabs. 

Go directly to the code: 

<script>
  document.addEventListener('visibilitychange', documentVisibilityChange)

  function documentVisibilityChange() {
    if(document.visibilityState === "hidden") {
      console.log('当前页签隐藏,即打开新页签')
    }
    if(document.visibilityState === "visible") {
      console.log('当前页签显示,即打开当前页签')
    }
  }
</script>

beforeunload 

beforeunload can monitor the closing of the page, and tab switching will not be triggered.

  • Triggered when the browser window is closed
  • Triggered when entering another page by clicking on the current address bar or favorites (note that it does not open a new tab)
  • Triggered when refreshing the browser
  • Triggered when the value of window.location.href is reassigned
  • Triggered when a form with a specified action is submitted through the form input type="submit" button (native event)

There may be other situations. If you are interested, you can learn more about it. I just used it when refreshing the browser. 

<script>
  window.addEventListener('beforeunload', windowBeforeUnload)

  function windowBeforeUnload() {
    console.log('触发beforeunload --->>>')
  }
</script>

Guess you like

Origin blog.csdn.net/m0_51431448/article/details/132087652