Javascript to detect if user changes tab

后端 未结 5 1849
无人共我
无人共我 2020-11-30 22:46


I want to write a webpage for online quiz.Basic requirement i have is that, If the person taking quiz changes tab or opens new window even without minimizing browser, i.

相关标签:
5条回答
  • In 2020 you can:

    document.addEventListener("visibilitychange", event => {
      if (document.visibilityState == "visible") {
        console.log("tab is activate")
      } else {
        console.log("tab is inactive")
      }
    })

    0 讨论(0)
  • 2020-11-30 23:25

    Best native function hands down, no jQuery.

    document.hasFocus
    

    Check the pen, check what happens when you go to the link and back to the codepen tab.

    https://codepen.io/damianocel/pen/Yxxzdj

    0 讨论(0)
  • 2020-11-30 23:40

    If you are targeting browsers that support it, you can use the Page Visibility API available in HTML5. It doesn't directly detect tab changes, per-say, but visibility changes. Which would include (but not limited to) tab changes.

    See https://developer.mozilla.org/en/DOM/Using_the_Page_Visibility_API

    0 讨论(0)
  • 2020-11-30 23:42

    You can determine if a tab or window is active by attaching a blur / focus event listener to window.

    in jQuery it would be

    $(window).focus(function() {
        //do something
    });
    
    $(window).blur(function() {
        //do something
    });
    

    quoted from this SO answer: https://stackoverflow.com/a/1760268/680578

    0 讨论(0)
  • 2020-11-30 23:46

    With jQuery:

    $(window).on('focus', function () {
    
    });
    
    $(window).on('blur', function () {
    
    });
    

    $().focus & $().blur are deprecated.

    0 讨论(0)
提交回复
热议问题