Sometimes you may want to take more control over your user Browser when he/she opens your website in a Browser Window.
For example – you want to know when the user closes the Browser Tab and execute your code.
Or you want to run the Animation only when the user is active otherwise stop it.
This kind of functionality you have seen in the websites or PTC sites which provide ads viewing to the users. They only count the ads view when the user is active on their website until given time otherwise they cancel the view after the specific time.
For finding the Browser Tab is currently active or not I defined two events on window –
- focus – for detecting active state, when this event trigger I start the timer
- blur – for detecting inactive, state. From where I stop the timer by clearing the Interval.
On focus event, you can define your code which you want to execute when it is active and within blur event define which you want to do when it is inactive.
Within the example, I use it to count the number of seconds the user active on the website. You can also this to pause the playing video or stop some the scripts when it is not using the website.