Is there a way to find out if the browser is active?

On my site, I have an important notice that triggers my own alert () to bring the site to the forefront if the window is not already focused. The problem is that in some browsers, if the user is in another desktop application (Photoshop, Microsoft Word, etc.), he will not use the browser on top of this application. In this case, the warning is pretty much useless, and I would like to omit it (since it blocks other scripts on my page).

Is there any way to say that the browser is an active application on the device? Or is there another, non-blocking way to bring a window to the fore?

Thanks!

Explanations: I already know how to check if the window in the browser is active, but I just do not know how to check if the browser application is active. Also, the browsers I need for support are Chrome, Safari, Firefox, and IE> = 9

+5
source share
3 answers

You can use the page visibility API for this.

It is compatible with IE 10+.

A small code example:

document.addEventListener("visibilitychange", function(e) { console.log("visibility changed!", e); if (document.visibilityState === 'visible') { console.info("window is visible now!"); } else { console.info("something else, maybe you changed tab or minimized window!"); } console.log("check the visibilityState property on document object for more info"); }); 

This will work even if the user minimizes the browser when the tab is open, so I assume this fits your needs :)

+2
source

You must use the new Notification object. It works even if the browser is not focused and useful for sending important user notifications.

Example: http://jsfiddle.net/howderek/792km8td/

 document.getElementById('notif').onclick = function () { function notify () { var notification = new Notification('Test!'); } if (Notification.permission === "granted") { setTimeout(notify, 5000); } else { Notification.requestPermission(function () { if (Notification.permission === "granted") { setTimeout(notify, 5000); } }); } } 

https://developer.mozilla.org/en-US/docs/Web/API/notification

+2
source

Have a global variable that keeps the window active or not:

 var window_active = true; 

Now add event listeners to "listen" for window activation (de):

 window.onblur = function () { window_active = false; }; window.onfocus = function () { window_active = true; }; 

And when you call the alert function, check that the global variable is:

 if (window_active) alert("notification"); 

I want to mention that if you change the tab or press url-bar, the window will be deactivated, which may not be what you want.

0
source

All Articles