0

Just as above - I need to get the last focused tab from a chrome extension popup context. The signature for such is: chrome.tabs.query(tabQueryOptions)

The only solution I have come up with is a listener or timeout that sets the last (non popup) focused tab in chrome storage, which is then referenced by the popup instead.

This isn't a great solution - I want my extension to have the lightest footprint possible.

I have tried the following, with issues on each:

  1. {lastFocusedWindow: true, active: true} (doesn't work when switching from another page and selecting popup/button)
  2. {active: true, currentWindow: true} (doesn't work when navigating from another window/tab)
  3. {pinned: true, active: true} (doesn't work, assumedly because when you select the popup it is no longer active
  4. {pinned: true} (request just falls into th ether, and assumedly would return a randomised list anyway)

CODE AND STEPS TO REPRODUCE BELOW:

popup.js

(async function onButtonClick(){
    document.getElementById('get_active_tab').addEventListener('click', async () => {
        chrome.runtime.sendMessage('get active tab pretty pleeeeease')
    })
})()

popup.html

<!DOCTYPE html>
<head>
</head>
<body>
    <div class="extension">
        <div class="selection__container">
            <button id="get_active_tab" style="height: 100%; width: 100%; font-size: 3rem">
                CLICK TO GET ACTIVE TAB
            </button>
        </div>
    </div>
</body>
<script src="popup.js">
</script>
</html>

manifest.json

{
"name": "Test Extension",
"description": "Testing Tab Query",
"version": "1.00",
"manifest_version": 3,
"background": {
    "service_worker": "background.js"
},
"permissions": [
    "storage",
    "activeTab",
    "identity",
    "contextMenus",
    "webRequest",
    "tabs",
    "clipboardWrite"
],
"host_permissions": [
    "<all_urls>"
],
"action": {
    "default_popup": "popup.html"
}

}

background.js

chrome.runtime.onMessage.addListener(async (message, sender, sendResponse) => {
    if(message === 'get active tab pretty pleeeeease'){
        let currentWindow = await chrome.windows.getCurrent()
        let [currentTab] = await chrome.tabs.query({active: true, windowId: currentWindow.id})
        console.log(`Current tab URL: ${currentTab.url}`)
        sendResponse(currentTab.url)
    }
})

STEPS TO REPRODUCE:

  1. Unpack extension locally
  2. Open a valid tab
  3. Open the popup/DevTools for logging, and click the button
  4. Open a new chrome window with a new valid tab(s)
  5. Open the popup and click again
  6. Observe the resultant logs
  7. switch between the windows/tabs, close one and observe result on other, etc
Callum
  • 11
  • 2
  • Assuming it's an `action` popup you can simply use {active:true, currentWindow:true} but if your popup is a separate window you should pass the tab id when creating this window e.g. as `url: 'popup.html?tabId=' + thisTab.id` where thisTab is the tab object for the active tab before creating the window, then inside the popup `const tabId = +new URLSearchParams(location.search).get('tabId')` – wOxxOm Jul 26 '23 at 10:24
  • It's an action popup, but {active:true, currentWindow:true} doesn't work when you switch from another window to the page, and immediately open the popup. – Callum Jul 26 '23 at 10:32
  • This scenario works for me. Maybe you've used lastFocusedWindow instead of currentWindow or it was an incognito window or a window from a different profile? Anyway, here's the workaround that should do the job: [Chrome tabs query returning empty tab array](https://stackoverflow.com/a/63886442) – wOxxOm Jul 26 '23 at 10:36
  • It only works when both the window and last active tab are the ones that the popup is currently selected in. Neither of these is a given, as selecting the popup action doesn't make the page active. – Callum Jul 26 '23 at 10:39
  • The page doesn't need to be active. It's the tab that becomes active when you click the icon. Did you try the workaround already? – wOxxOm Jul 26 '23 at 10:40
  • Yep I already tried it - I read every related question on stack exchange before posting, which is why it's a little perplexing that my question has been closed... My code is: let tabQueryOptions = {active:true, currentWindow:true}, [tab] = await chrome.tabs.query(tabQueryOptions) and I log the tab URL when selecting the popup button. I have confirmed that the tab only becomes active when the page has been clicked into since last switching to another window/tab, and when you haven't switched to another window in the meantime (e.g. using alt-tab). Otherwise, different URLs appear. – Callum Jul 26 '23 at 10:51
  • Thinking about it, even setting event listeners for tab changes, or timeouts to log last active, wouldn't work. I may have to change the setup for the user to select a list of tabs out of {pinned: true, windowType: 'normal'}. – Callum Jul 26 '23 at 10:53
  • 1) Are you sure you've used the workaround I linked? It's using two API calls. 2) It's becoming unclear what happens. It may be a bug in Chrome or some essential detail is missing in your description. Maybe you can make a screen recording or provide an exact sequence of steps with code? – wOxxOm Jul 26 '23 at 10:58
  • It's also unclear how pinned tabs are related and why you say that the action popup is a tab itself because it's not, assuming it's really an `action` popup. – wOxxOm Jul 26 '23 at 11:07
  • I'm using page and tab interchangeably, and apologies if i got something wrong in describing it, but I guarantee that the solution doesn't work. Niether does using the active window, as interacting with the extension icon and clicking inside the popup does not make the window it is on the one returned by windows.getCurrent(). Infact it seemed to confuse it even more, by refusing to recognise the current window, even with interaction, without first closing all my other windows. – Callum Jul 26 '23 at 11:18
  • The solutions I suggested work for all existing extensions in all cases I know of over the past ~10 years of developing and supporting extensions. I can't reproduce the problem you've described and not aware of a bug report about it. I can't help without an exact sequence of actions and code or an extension. – wOxxOm Jul 26 '23 at 11:23
  • I understand, and thanks for the help - I will post complete code to replicate – Callum Jul 26 '23 at 11:26

0 Answers0