Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect browser focus/out-of-focus via Google Chrome Extension

Is there a way to find out if Google chrome is in focus or out of focus? I'm creating an app which needs to know if the user is currently using the browser or not.

By tying the detection through the content script in a Google extension, I've tried using blur and focus but the problem is that clicking on the address bar also fires a blur event. Same goes for detecting mouse movement, where moving the mouse outside of the viewing area will not be detected.

I've also tried looking at onFocusChanged but it seems it only detects changes in chromes' windows not apps outside of Chrome.

Anyone have other ideas for this? Also, would this be any easier if I created an add-on for firefox instead?

Thanks!

like image 343
Paul Avatar asked Apr 04 '10 11:04

Paul


4 Answers

You can use the chrome.windows API to monitor this. You would add a listener for the onFocusChanged event and if the event returned -1 or chrome.windows.WINDOW_ID_NONE then you know that the browser lost focus:

var inFocus = true;  // global boolean to keep track of state
chrome.windows.onFocusChanged.addListener(function(window) {
    if (window == chrome.windows.WINDOW_ID_NONE) {
        inFocus = false;
    } else {
        inFocus = true;
    }
});

Chrome.Window Doc

like image 188
J Max Avatar answered Oct 02 '22 13:10

J Max


Maybe some don't see @Giedrius' comment. This interval works:

window.setInterval(checkBrowserFocus, 1000);  

function checkBrowserFocus(){

    chrome.windows.getCurrent(function(browser){

      console.log(browser.focused)

    })

}
like image 24
Claudiu Creanga Avatar answered Oct 02 '22 14:10

Claudiu Creanga


setInterval(function() {
    chrome.windows.getLastFocused(function(window) {
        console.log(window.id.toString() + "  " + window.focused.toString())
    });
}, 1000);

or:

setInterval(function() {
    chrome.windows.getCurrent(function(window) {
        console.log(window.id.toString() + "  " + window.focused.toString())
    });
}, 1000);

window.focused is false means that no chrome window is focused.

reference:https://developer.chrome.com/extensions/windows

like image 45
geekgao Avatar answered Oct 02 '22 13:10

geekgao


Yes, this is done by manipulating the blur and focus event. Like this example in jQuery:

$(window).blur(function(){
    // do something when it loose focus like that:
    alert('Good Bye.');
});

$(window).focus(function(){
    // do something when it gains focus
    alert('Welcome back.');
});
like image 21
Augusto Will Avatar answered Oct 02 '22 13:10

Augusto Will