Search code examples
google-chromegoogle-chrome-extensionfocuswindow

Chrome Extension - Chrome.windows.onFocusChanged Behavior


I'm trying to make an extension for Google chrome which requires me to be able to identify the currently selected tab. I did this with the chrome.tabs.onSelectionChanged method, however when I switch windows this isn't fired. I plan to use chrome.windows.onFocusChanged to detect when the window changes then use the chrome.tabs.getSelected method. However the problem is that chrome.windows.onFocusChanged seems to be fired more than once. If I'm not mistaken, it returns window -1, then the first window created (usually 1), then the current window. If the first window is selected then it's fires -1, then 1.

Am I using the right method here? Is there a better way of doing this? If I stick with it I might need to keep track of how window changes which is a bit messy.


Solution

  • Kinda worked on my own solution for this. For anyone interested in doing something similar, what I did instead was to use the onFocusChanged as an indicator that there is a window change happening which then starts a requestListener. Using content scripts, I sent a request to the extension whenever there was a window.focus event indicating that the focus is already on that window. The requestlistener then just removes itself. Unfortunately this approach requires all tabs to send requests every time they get focus. Some more tweaking to fix that I guess but for the mean time I think that suffices since sending requests every time there is a change of focus doesn't seem to eat up that much resources.