I'm trying to make a webpage that helps you concentrate on your work by giving you points while you are on a webpage. I need something to display a message saying "You lost" or something like that when someone switches tabs . Being fairly new to web design, I'm unable to get this. Can someone please help?
Asked
Active
Viewed 754 times
-1
-
1Possible duplicate of [Detect if browser tab is active or user has switched away](https://stackoverflow.com/questions/19519535/detect-if-browser-tab-is-active-or-user-has-switched-away) – yuriy636 Aug 11 '17 at 14:29
-
1https://developer.mozilla.org/en-US/docs/Web/API/Page_Visibility_API – epascarello Aug 11 '17 at 14:29
-
Welcome to StackOverflow. Questions seeking help must include the desired behavior, a specific problem or error and the shortest code necessary to reproduce it in the question itself and show effort. Questions without a clear problem statement are not useful to other readers. See: How to create a Minimal, Complete, and Verifiable example. – serdar.sanri Aug 11 '17 at 14:29
-
Possible duplicate of [Javascript to detect if user changes tab](https://stackoverflow.com/questions/10338704/javascript-to-detect-if-user-changes-tab) – ControlAltDel Aug 11 '17 at 14:30
3 Answers
1
I would recommend using window.onblur event.The onblur event occurs when an object loses focus.Object in this case would be window
use this code snippet :
window.onblur = function () {
alert('trying to switch tabs eh !');
};
EDIT : see this jsfiddle for a working demo, i've tested on chrome !

Ankit
- 5,733
- 2
- 22
- 23
-
Thanks a lot! But since I'm just a newbie to js, could you please tell me a bit more how to use it? – dadum dadum Aug 11 '17 at 15:08
-
-
Thanks Ankit! This is what I was looking for! Our main coder just switched sides and we're just left with some design artists now . Really needed this! – dadum dadum Aug 11 '17 at 15:55
0
You can attach to your window a focus or a blur event in jquery :
$(window).focus(function() {
// your actions
});
But it's only on your website... You can build a browser extension if you wana check every pages.

Kall Drogo
- 56
- 7
0
Pure JS, all browsers, hasFocus()
if ( document.hasFocus()
Check the link what happens when you open a new page with the button:-)

ptts
- 1,022
- 8
- 18