80


I am writing a webpage for online quiz. The basic requirement I have is that it must fire an event(stopping the quiz) if the user changes tabs or opens a news window even without minimizing their browser, i.e if the person is attempting to see the answer from some other window/tab. How can I do that?

Note : Try to avoid including a bleeding edge HTML5 feature in your answer because I want the feature to be supported by all major browsers currently.

Debug Diva
  • 26,058
  • 13
  • 70
  • 123
Maxsteel
  • 1,922
  • 4
  • 30
  • 55
  • 1
    Well certainly change in tab can be detected by using Javascript as far as i know.What i wanted to know is, if the change in focus of the window like opening a new browser can be detected! – Maxsteel Apr 26 '12 at 17:52
  • You won't detect if it happens in another browser window. – Denys Séguret Apr 26 '12 at 17:53

8 Answers8

88

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

Community
  • 1
  • 1
Kristian
  • 21,204
  • 19
  • 101
  • 176
85

In 2022 you can use an event listener with the visibilitychange event:

document.addEventListener("visibilitychange", (event) => {
  if (document.visibilityState == "visible") {
    console.log("tab is active")
  } else {
    console.log("tab is inactive")
  }
});
unrealapex
  • 578
  • 9
  • 23
Bart Blast
  • 959
  • 6
  • 6
  • While the 'Page Visibility API' mozilla docs don't reference this specifically, I tried this approach to check if a User has logged out on another browser tab and, if so, then updates the displayed login info when the User comes back to a tab. It seems to work well. Is this the correct method to check login status or is there a better way? – ND_Coder Dec 01 '22 at 12:00
37

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

Matt
  • 41,216
  • 30
  • 109
  • 147
  • 1
    This is a handy API however it should be noted that at this time (March 6, 2015) there are some limitations: `Alt` + `Tab` (e.g. app switching on of any kind) doesn't register on Windows for Firefox/Chrome/IE10. Switching tabs within each browser does work just fine though. On iOS though app switching or device locking **does** trigger a visibility change. – scunliffe Mar 06 '15 at 15:45
31

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

ptts
  • 1,022
  • 8
  • 18
8

window onfocus and onblur work just fine:

window.onfocus = function (ev) {
    console.log("gained focus");
};

window.onblur = function (ev) {
    console.log("lost focus");
};
shieldgenerator7
  • 1,507
  • 17
  • 22
  • 1
    This has the advantage over 'visibilitychange' event that it is triggerred after browser's window gained / lost focus while 'visibilitychange' works only on tab switching – Kamil Bęben Mar 25 '22 at 15:14
  • This won't work though if say the code is inside of a iframe and the user clicks the main page. It will cause it to pause still – Derek Lawrence Nov 07 '22 at 07:12
5

With jQuery:

$(window).on('focus', function () {

});

$(window).on('blur', function () {

});

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

472084
  • 17,666
  • 10
  • 63
  • 81
1

Working on a similar project. This worked the best. On the highest level component which wouldn't normally rerender, add:

  setInterval( checkFocus, 200 );

  function checkFocus(){
    if(document.hasFocus()==false){
      //Do some checking and raise a red flag if this runs during an exam.
    }
  }
Sadequs Haque
  • 158
  • 10
0

I needed something like this and it seems this behavior is slightly different on each browser.

    if (document.hidden !== undefined) { // Opera 12.10 and Firefox 18 and later support     
      visibilityChange = "visibilitychange";
    } else if (document.mozHidden !== undefined) {      
      visibilityChange = "mozvisibilitychange";
    } else if (document.msHidden !== undefined) {      
      visibilityChange = "msvisibilitychange";
    } else if (document.webkitHidden !== undefined) {      
      visibilityChange = "webkitvisibilitychange";
    } else if (document.oHidden !== undefined) {      
      visibilityChange = "ovisibilitychange";
    }
    
    document.addEventListener(visibilityChange, function(event) {
      handleVisibilityChange();
    }, false);

I have an example you can check: https://jsfiddle.net/jenol/4g1k80jq/33/

Jeno Laszlo
  • 2,023
  • 18
  • 36