Extension Tab ID, Window Context, and Tab API Operations
How browser extensions use tabId and windowId: query the active tab, run tab/window APIs, permissions, and common async mistakes.
This page summarizes Chrome extension documentation on tabId and related windowId values: how identifiers are assigned, how to find the user’s current tab, which APIs accept a tab argument, and what permissions affect tab metadata. The same patterns appear across the browser.* namespace (Promise-based) and the legacy chrome.* namespace (Promises with optional callbacks).
tabId: what it identifies and when it is missing
Section titled “tabId: what it identifies and when it is missing”A tabId is the numeric ID of a browser tab. On the tabs.Tab object, id is optional because a tab is not always assigned an ID.
The ID of the tab. Tab IDs are unique within a browser session. Under some circumstances a tab may not be assigned an ID; for example, when querying foreign tabs using the sessions API, in which case a session ID may be present. Tab ID can also be set to chrome.tabs.TAB_ID_NONE for apps and devtools windows.
— Google, tabs API (browser)
Each tab also carries windowId: the ID of the window that contains it. groupId links the tab to a tab group; splitViewId links paired tabs in a Split View. For closed entries restored via browser.sessions, use sessionId instead of a live tabId.
| Identifier | Scope | Typical use |
|---|---|---|
tabId |
Unique per browser session | tabs.get, tabs.update, action.enable(tabId) |
windowId |
Unique per browser session | windows.get, tabs.query({ windowId }) |
sessionId |
Closed tab/window in session history | sessions.restore(sessionId) |
groupId |
Tab group in session | tabGroups.get, tabs.group |
tabs.query: how to get the current or active tab
Section titled “tabs.query: how to get the current or active tab”Extensions usually start by resolving “the tab the user cares about” with browser.tabs.query. The documented pattern for the current tab (active tab in the focused—or last focused—window) is:
async function getCurrentTab() { let queryOptions = { active: true, lastFocusedWindow: true }; let [tab] = await browser.tabs.query(queryOptions); return tab;}This example demonstrates how an extension’s service worker can retrieve the active tab from the currently-focused window (or most recently-focused window, if no Chrome windows are focused). This can usually be thought of as the user’s current tab.
— Google, tabs API (browser)
Important distinctions from tabs.Tab fields:
active— tab is active in its window; the window need not be focused.highlighted— tab is in the current selection (replace deprecatedselected).lastFocusedWindow: trueinqueryInfo— limit to the last focused Chrome window when the user alt-tabs away.
tabs.getCurrent() returns the tab whose script is running (popup, content script context). It returns undefined from a service worker or other non-tab context—unlike query({ active: true, … }).
URL and title matching in queries
Section titled “URL and title matching in queries”queryInfo.url and queryInfo.title are only honored if the extension has the "tabs" permission or host permissions for the page. Without them, those filters are ignored and sensitive fields may be absent on returned objects.
windowId: current window vs focused window
Section titled “windowId: current window vs focused window”Many methods default tabId or windowId to the “selected” or “current” window. browser.windows defines current window differently from the topmost window:
The current window is the window that contains the code that is currently executing. It’s important to realize that this can be different from the topmost or focused window.
— Google, windows API (browser)
In the case of service workers, the value of the current window falls back to the last active window.
— Google, windows API (browser)
Use windows.getLastFocused() when you need the window that was most recently focused—typically on top. Use windows.getCurrent() when behavior should follow the caller’s window (for example a popup calling tabs.query with currentWindow: true). The constant windows.WINDOW_ID_CURRENT represents the current window in queryInfo.
With queryOptions.populate: true, windows.get can include a tabs array; tab url, title, and favIconUrl in that list require "tabs" in the manifest.
Asynchronous APIs: why tabId must come from a callback or await
Section titled “Asynchronous APIs: why tabId must come from a callback or await”Most extension APIs do not return tab data synchronously. The architecture overview shows that calling chrome.tabs.query without a callback does not yield a tab ID:
This approach will fail because query() is asynchronous. It returns without waiting for the work to complete, and does not return a value.
— Google, Architecture overview
Correct flow: query → receive tabs[0].id in the callback or awaited Promise → pass that tabId to tabs.update, tabs.move, or other methods. Synchronous-style helpers such as chrome.runtime.getURL() return a string immediately and take no callback—unlike tab APIs.
In Promise code, handle failures explicitly; the tabs docs note that catching Promise errors avoids leaving runtime.lastError unchecked when tab edits fail (for example during a drag).
tabs API: create, update, move, and close by tabId
Section titled “tabs API: create, update, move, and close by tabId”browser.tabs is the main surface for lifecycle operations once you have an ID (or index within a window).
| Method | Role of tabId |
|---|---|
tabs.get(tabId) |
Read mutedInfo, url, pinned, etc. |
tabs.update(tabId?, props) |
Navigate (url), mute, pin, set active (omitted tabId → selected tab in current window) |
tabs.move(tabIds, …) |
Reorder or move to another normal window |
tabs.remove(tabIds) |
Close one or more tabs |
tabs.duplicate(tabId) |
Clone a tab |
tabs.group({ tabIds, groupId? }) |
Assign tabs to a group; returns groupId |
Navigation via update({ url }) does not support JavaScript URLs; the docs direct you to scripting.executeScript instead. Fully qualified URLs need a scheme (for example https://…).
tabs.create accepts optional openerTabId (opener must be in the same window as the new tab) and windowId for the target window. tabs.reload and tabs.discard default to the active tab of the current window when tabId is omitted.
User interaction limits
Section titled “User interaction limits”tabs.move can fail while the user drags a tab:
Error: Tabs cannot be edited right now (user may be dragging a tab).
— Google, tabs API (browser)
The documented mitigation is to retry after a short delay. Tabs can only move between windows whose type is normal.
Other extension APIs that take tabId
Section titled “Other extension APIs that take tabId”Dozens of APIs thread the same tabId parameter. Grouped by purpose:
Toolbar and UI
browser.action.enable/disable(tabId?)— per-tab toolbar button state (MV2:chrome.browserAction).browser.sidePanel—open,close, and options keyed bytabIdand/orwindowId(at least one required; tab-specific vs global panel behavior changed in recent Chrome versions per the API reference).
Capture, storage, and debugging
browser.pageCapture— MHTML save requirestabId.browser.tabCapture— events includetabIdfor the affected tab.browser.devtools.inspectedWindow— exposes the inspected tab’s ID for use withchrome.tabs.*.browser.cookies— a cookie store liststabIdssharing that store.
Search, sessions, and processes
browser.search.query— optionaltabIdinQueryInfo(cannot combine withdisposition).browser.sessions.restore(sessionId?)— restores a tab or window; closed tabs may exposesessionIdinstead oftabId.browser.processes.getProcessIdForTab(tabId)— renderer process ID for a tab.
Networking and navigation
browser.declarativeNetRequest— action counts keyed bytabId.browser.webNavigation— frame and tab-replacement events carrytabId/replacedTabId.
Extension views
browser.extension.getViews({ tabId })— locate an extension page tied to a tab (foreground only).browser.runtime.getBackgroundPageis deprecated and does not apply to MV3 service workers.
Tab groups, split views, and resource states
Section titled “Tab groups, split views, and resource states”browser.tabGroups manages groups by groupId; each member tab’s groupId updates when grouped via tabs.group. Split View APIs pair exactly two adjacent tabs with matching windowId, pinned, and groupId (tabs.create / createSplit in the MV2 reference).
Resource-related flags on tabs.Tab matter when passing IDs into discard or reading state:
discarded— content unloaded; reloads on activation.frozen— no JS tasks until activation.autoDiscardable— whether the browser may discard under memory pressure.audiblevsmutedInfo.muted— sound production vs mute indicator.
Permissions and sensitive tab fields
Section titled “Permissions and sensitive tab fields”Fields such as url, pendingUrl, title, and favIconUrl on a tab object require the "tabs" permission or matching host permissions. The same rule applies when populating windows with nested tabs (windows query options).
tabs.captureVisibleTab (MV2 reference) captures the active tab in a window and needs <all_urls> or activeTab; sensitive schemes are only allowed with activeTab.
Common mistakes
Section titled “Common mistakes”- Treating
tabs.queryas synchronous and using its return value as a tab object (see architecture overview). - Assuming
active: truemeans the browser window is focused—checklastFocusedWindowor window APIs. - Using
getCurrent()in a service worker expecting the user’s tab—it only works from tab contexts (tabs.getCurrent). - Filtering by URL or title without
"tabs"or host permissions—filters are ignored. - Calling
tabs.moveortabs.updateduring a user drag without retry logic. - Passing
tabIdtosearch.querytogether withdisposition—the API forbids that combination. - Relying on
getBackgroundPagein MV3—background pages do not exist; the method is deprecated (runtime.getBackgroundPage).
How to check this on your site
Section titled “How to check this on your site”-
Load your extension unpacked in Chrome, open the tabs API reference, and add a temporary
console.logafterbrowser.tabs.query({ active: true, lastFocusedWindow: true })to confirm you receive a numericidand expectedwindowId. -
From a popup and from the service worker, log
browser.windows.getCurrent()versusbrowser.windows.getLastFocused()and compare IDs when another application has OS focus (windows API). -
Toggle manifest permissions (
"tabs"vs host-only), reload the extension, and verify whethertab.url/tab.titleappear on queried tabs and onwindows.getwithpopulate: true. -
Trigger
tabs.movewhile dragging a tab in the UI and confirm your error handling matches the documented retry pattern (tabs examples). -
You can check automatically in Answerwell (our tool): https://answerwell.org/workspace
Report an error or ask a question
Section titled “Report an error or ask a question”If something on this page is wrong or unclear, email yimasynthetic@gmail.com with the page URL and the exact statement you are asking about.