I want to detect in a Chrome extension background script what is the active browser tab with focus if any.
I have the code below that works in almost all cases. However, if I restore a minimized app (eg. Outlook) that hides the browser window then the onFocusChange event doesn't fire.
chrome.windows.onFocusChanged.addListener((windowId) => {
console.log('On focus change: ' + windowId);
handleActiveTab();
});
chrome.tabs.onActivated.addListener((e) => {
console.log('On activated', e);
handleActiveTab();
});
chrome.tabs.onUpdated.addListener((e) => {
console.log('On updated', e);
handleActiveTab();
});
const handleActiveTab = () => {
chrome.tabs.query({ active: true, currentWindow: true, lastFocusedWindow: true }, function (tabs) {
if (tabs[0]) {
chrome.windows.get(tabs[0].windowId, (w) => {
if (w && w.focused) {
console.log('ACTIVE TAB -> ' + tabs[0].url);
} else {
console.log('ACTIVE TAB WITHOUT FOCUS -> ' + tabs[0].url);
}
});
} else {
console.log('NO ACTIVE TAB');
}
});
};
If I call my handleActiveTab with a timer then it detects, that the browser tab lost the focus. The window.focused property changes. But why the onFocusChanged event is not fired?
As a workaround, I can use the solution with a timer, but I would like to avoid it if possible.