DEV Community

Cover image for How to Detect Idle Browser Tabs with JavaScript

How to Detect Idle Browser Tabs with JavaScript

vorillaz on March 22, 2020

In some cases, we can found ourselves doing lots of intensive, CPU hungry tasks while the users are interacting with our end products or applicatio...
Collapse
 
chautelly profile image
John

I've used this API to detect if a blur event on an input was due to tabbing and prevent showing an invalidation message if the input was left in an invalid state since tabbing back will give it back it's focus.

Collapse
 
vorillaz profile image
vorillaz

That’s a great example and use case of the API. Thanks a lot for the reply John.

Collapse
 
jalners profile image
Alexey Neretin

Thanks for this article. I would like to propose a little fix.

Try to do next:

  • Add your Example with Polling on the page.
  • Reload the page and switch a browser tab before your sample will be reloaded.
  • Wait until your page with sample will be reloaded.
  • Go back to your page.
  • You will see that poller calls console.log twice as often.
  • Try to stop the poller. It will work even after poller.stop() call.

This is due to double call of the poller.start. For the first time from your sample code. The second time you call it from the onVisibilityChange. There was no poller.stop method call between double poller.start method call in this case.

You can avoid it by calling the poller.stop method before the poller.start in the onVisibilityChange.

Collapse
 
nikosdev profile image
Nikos Kanakis

Nice article !