31 Oct 2015

How to detect if user is away from web page using Page Visibility API JavaScript

In this simple tutorial we are going to learn how to detect if user is away from your website and if true then alert our user. Remember what i understand that here Away and idle are two different things,
Away means user has opened your web page but not using it as he or she is on different web page opened in different tab and other case is web browser is minimized! and Idle is same as Away but difference is we can also say that user is Idle if he has opened your web page but not doing any activity on your web page!
Detecting Idle state is different task here i am only concerning about Away state :)

So to detect if user is away from your website we have to do something which is responsible to continuously check user state for this purpose JavaScript's setInterval is so handy! as setInterval keep calling its callback function after given amount of time, if you are not familiar with setInterval kindly read this tutorial.
And other thing we are going to use is Page Visibility API of JavaScript if you don't know about it you can learn here!

 
setInterval(function() {
  if(document.visibilityState == "hidden")
    {
        alert("hey you why you go away from my site ? ");    
    } 
},1000);
 

Above function checks visibility state of document after every one second! and if its hidden then it will quickly alert our user :)
check yourself here!

There are so many possibilities with Visibility API as if you have a website with login and logout procedure you can detect if user is away from particular time period you can also logout your user!
so keep coding and have fun! :)

 

No comments:

Post a Comment