6

I'd like to be able to mute activity of my app if I can detect that the page is no longer focused. For instance, if the page is in a background tab or another app has focus, I'd like to disable a constantly polling script or switch modal notifications to the new HTML5 notifications API.

Is there any way to get this with JS, and if so, which browsers are supported?

PS - I've seen this, but don't know if it would work for what I'm looking to do. Anybody have any insight?

Community
  • 1
  • 1
mattbasta
  • 13,492
  • 9
  • 47
  • 68
  • 1
    There is a new API called Page Visibility API. See [How to know a browser is minimized in javascript](https://stackoverflow.com/a/64229054/11667949) – Shivam Jha Oct 06 '20 at 15:34

1 Answers1

15

You can listen for the blur event on your window, then for when the user comes back, you can use the focus event:

Here's an example in jQuery:

$(window).blur(disableStuff).focus(enableStuff);

Or in pure JavaScript:

window.onblur = disableStuff;
window.onfocus = enableStuff;
Jacob Relkin
  • 161,348
  • 33
  • 346
  • 320