On my site I have an important notification that prompts a native alert() in order to bring the site to the foreground if the window is not already focused. The problem is that on some browsers, if the user is in another desktop application (Photoshop, Microsoft Word, etc), it will not bring the browser on top of that application. In this case the alert is pretty much useless and I would like to omit it (since it blocks the other scripts on my page).
Is there a way to tell that a browser is the active application on a device? Or is there a different, non-blocking way to bring a window to the foreground?
Thanks!
Clarifications:
I already know how to check if a window is active within a browser, but I just don’t know how to check if the browser application itself is active.
Also, browsers I need to support are Chrome, Safari, Firefox, and IE >= 9
3
Answers
Have a global variable storing whether the window is active or not:
Now add event listeners to “listen” for window (de)activation:
And when you call the
alert
function, check that global variable:I want to mention that if you change the tab or click the url-bar, the window will be deactivated, which might be not what you want.
You should use the new
Notification
object. It works even when the browser is not focused, and is useful for sending the user important notifications.Example: http://jsfiddle.net/howderek/792km8td/
https://developer.mozilla.org/en-US/docs/Web/API/notification
You can use the Page Visibility API for this.
It is compatible with IE 10+.
Small example of code:
This will work even if the user minimizes the browser while the tab is open, so I guess this suits your needs 🙂