Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript to detect if user changes tab


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.

like image 504
Maxsteel Avatar asked Apr 26 '12 17:04

Maxsteel


People also ask

Can websites detect switching tabs?

Modern websites use multiple "event listeners" and can detect every move the user is executing. So, if a user switches the tab or hovers over to another tab, it can gather the data and see whether the user stayed on the web page or not. A website can detect this anomaly by using cookies and IDs.

How can I find out if someone is leaving a website?

Try the onbeforeunload event: It is fired just before the page is unloaded. It also allows you to ask back if the user really wants to leave. See the demo onbeforeunload Demo. Alternatively, you can send out an Ajax request when he leaves.


2 Answers

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

like image 119
Kristian Avatar answered Oct 08 '22 17:10

Kristian


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")   } });
like image 44
Bart Blast Avatar answered Oct 08 '22 18:10

Bart Blast