Recently browsing site B found a small feature implementation. When we’re watching a video, if we cut to another TAB or minimize, the video will pause automatically; When it switches back, the video continues to play, as does the same audio. So how does that work? I looked for information and sorted it out myself.

  • Document. The hidden attribute

The document.hidden property, which displays whether the page is the one the user is currently viewing, is of Boolean type, true or false.

  • Visibilitychange event

This event listens for page display and hide and can be handled logically in the event’s callback function.Chrome and Firefox are supported.

The code is as follows:

<! DOCTYPEhtml>
<html>
<head>
  <meta charset="UTF-8">
  <title>Switch web page operation audio and video</title>
</head>

<body>
  <audio id="audio" controls="controls"><source src="test.mp3" type="audio/mp3" /></audio>
  <video id="video" width="320" height="240" controls><source src="test.mp4" type="video/mp4" /></video>
</body>

<script>
  let title = ' '
  const audioDom = document.querySelector('#audio')
  const videoDom = document.querySelector('#video')

  document.addEventListener('DOMContentLoaded'.() = > {
    title = document.title
  })

  document.addEventListener('visibilitychange'.() = > {
    if (document.hidden) {
      document.title = 'Automatic pause'
      audioDom.pause()
      videoDom.pause()
    } else {
      document.title = 'Resume play'
      audioDom.play()
      videoDom.play()
      setTimeout(() = > {
        document.title = title
      }, 1500)}})</script>
</html>

Copy the code