fix(extension): resolve active tab/window per caller context
This commit is contained in:
@@ -7,6 +7,39 @@ const PREFIX = '[TabsController.background]'
|
||||
|
||||
const debug = console.debug.bind(console, `\x1b[90m${PREFIX}\x1b[0m`)
|
||||
|
||||
/**
|
||||
* Resolve active tab.
|
||||
*
|
||||
* - `tabs.query({ active: true })` does not work in multi-window scenarios.
|
||||
* - Extension pages (side panel, hub tab) can resolve their own windowId.
|
||||
* We just find the active tab within that window.
|
||||
* - Content scripts (PAGE_AGENT_EXT) can't self-report a windowId.
|
||||
* Chrome populates `sender.tab` for every content-script message,
|
||||
* which is the tab hosting the script.
|
||||
*/
|
||||
async function resolveActiveTab(
|
||||
payload: { windowId?: number } | undefined,
|
||||
sender: chrome.runtime.MessageSender
|
||||
): Promise<chrome.tabs.Tab> {
|
||||
const windowId = payload?.windowId
|
||||
|
||||
if (windowId != null) {
|
||||
debug('get_active_tab: resolving via caller-reported windowId', windowId)
|
||||
const [tab] = await chrome.tabs.query({ active: true, windowId })
|
||||
if (!tab) throw new Error(`No active tab found in window ${windowId}.`)
|
||||
return tab
|
||||
}
|
||||
|
||||
if (sender.tab) {
|
||||
debug('get_active_tab: resolving via sender.tab (content script)', sender.tab.id)
|
||||
return sender.tab
|
||||
}
|
||||
|
||||
throw new Error(
|
||||
'Cannot resolve active tab: caller reported no windowId and is not a content script (no sender.tab).'
|
||||
)
|
||||
}
|
||||
|
||||
export function handleTabControlMessage(
|
||||
message: { type: 'TAB_CONTROL'; action: TabAction; payload: any },
|
||||
sender: chrome.runtime.MessageSender,
|
||||
@@ -16,12 +49,11 @@ export function handleTabControlMessage(
|
||||
|
||||
switch (action as TabAction) {
|
||||
case 'get_active_tab': {
|
||||
debug('get_active_tab')
|
||||
chrome.tabs
|
||||
.query({ active: true })
|
||||
.then((tabs) => {
|
||||
debug('get_active_tab: success', tabs)
|
||||
sendResponse({ success: true, tab: tabs[0] })
|
||||
debug('get_active_tab', payload)
|
||||
resolveActiveTab(payload, sender)
|
||||
.then((tab) => {
|
||||
debug('get_active_tab: success', tab)
|
||||
sendResponse({ success: true, tab })
|
||||
})
|
||||
.catch((error) => {
|
||||
sendResponse({ error: error instanceof Error ? error.message : String(error) })
|
||||
@@ -46,7 +78,7 @@ export function handleTabControlMessage(
|
||||
case 'open_new_tab': {
|
||||
debug('open_new_tab', payload)
|
||||
chrome.tabs
|
||||
.create({ url: payload.url, active: false })
|
||||
.create({ url: payload.url, windowId: payload.windowId, active: false })
|
||||
.then((newTab) => {
|
||||
debug('open_new_tab: success', newTab)
|
||||
sendResponse({ success: true, tabId: newTab.id })
|
||||
|
||||
Reference in New Issue
Block a user