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!
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
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)
})
}
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
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.');
});
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