search

Home  >  Q&A  >  body text

javascript - How to tell if the user has switched to the current tab?

I noticed that YouTube will only start playing the video when the user switches to the current tab.
So when a user opens multiple tabs, how to determine whether the user has switched to the current tab?

三叔三叔2697 days ago857

reply all(2)I'll reply

  • 高洛峰

    高洛峰2017-07-05 10:40:13

    There is a Page Visibility API, you can take a look

    I have thought about this implementation before, but it actually has shortcomings. What if sometimes I just want to listen to the sound? (:evil

    reply
    0
  • 天蓬老师

    天蓬老师2017-07-05 10:40:13

    document.addEventListener('visibilitychange', function() {
        if (!document.hidden) {
            // code
        }
    })

    reply
    0
  • Cancelreply