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
You can use the Page Visibility API for this.
It is compatible with IE 10+.
Small example of code:
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 while the tab is open, so I guess this suits your needs :)
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With