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.
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.
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.
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
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") } });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With