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:
- {lastFocusedWindow: true, active: true} (doesn't work when switching from another page and selecting popup/button)
- {active: true, currentWindow: true} (doesn't work when navigating from another window/tab)
- {pinned: true, active: true} (doesn't work, assumedly because when you select the popup it is no longer active
- {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:
- Unpack extension locally
- Open a valid tab
- Open the popup/DevTools for logging, and click the button
- Open a new chrome window with a new valid tab(s)
- Open the popup and click again
- Observe the resultant logs
- switch between the windows/tabs, close one and observe result on other, etc