-1

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?

  • 1
    Possible 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
  • 1
    https://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 Answers3

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
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:-)

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

ptts
  • 1,022
  • 8
  • 18