Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to tell if a browser is active?

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

like image 258
Tatermelon Avatar asked Sep 29 '22 06:09

Tatermelon


2 Answers

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 :)

like image 144
user3459110 Avatar answered Oct 05 '22 06:10

user3459110


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/

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

like image 26
howderek Avatar answered Oct 05 '22 06:10

howderek