chrome.tabs (original) (raw)

Skip to main content

chrome.tabs

Description

Use the chrome.tabs API to interact with the browser's tab system. You can use this API to create, modify, and rearrange tabs in the browser.

The Tabs API not only offers features for manipulating and managing tabs, but can also detect thelanguage of the tab, take a screenshot, andcommunicate with a tab's content scripts.

Permissions

Most features don't require any permissions to use. For example: creating a new tab,reloading a tab, navigating to another URL, etc.

There are three permissions developers should be aware of when working with the Tabs API.

The "tabs" permission

This permission does not give access to the chrome.tabs namespace. Instead, it grants an extension the ability to call tabs.query() against four sensitive properties on tabs.Tab instances: url, pendingUrl, title, andfavIconUrl.

{
  "name": "My extension",
  ...
  "permissions": [
    "tabs"
  ],
  ...
}

Host permissions

Host permissions allow an extension to read and query a matching tab's four sensitivetabs.Tab properties. They can also interact directly with the matching tabs using methods such as tabs.captureVisibleTab(),scripting.executeScript(), scripting.insertCSS(), andscripting.removeCSS().

{
  "name": "My extension",
  ...
  "host_permissions": [
    "http://*/*",
    "https://*/*"
  ],
  ...
}

The "activeTab" permission

activeTab grants an extension temporary host permission for the current tab in response to a user invocation. Unlike host permissions, activeTab does not trigger any warnings.

{
  "name": "My extension",
  ...
  "permissions": [
    "activeTab"
  ],
  ...
}

Use cases

The following sections demonstrate some common use cases.

Open an extension page in a new tab

A common pattern for extensions is to open an onboarding page in a new tab when the extension is installed. The following example shows how to do this.

background.js:

chrome.runtime.onInstalled.addListener(({reason}) => {
  if (reason === 'install') {
    chrome.tabs.create({
      url: "onboarding.html"
    });
  }
});

Get the current 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.

  async function getCurrentTab() {
    let queryOptions = { active: true, lastFocusedWindow: true };
    // `tab` will either be a `tabs.Tab` instance or `undefined`.
    let [tab] = await chrome.tabs.query(queryOptions);
    return tab;
  }
  function getCurrentTab(callback) {
    let queryOptions = { active: true, lastFocusedWindow: true };
    chrome.tabs.query(queryOptions, ([tab]) => {
      if (chrome.runtime.lastError)
      console.error(chrome.runtime.lastError);
      // `tab` will either be a `tabs.Tab` instance or `undefined`.
      callback(tab);
    });
  }

Mute the specified tab

This example shows how an extension can toggle the muted state for a given tab.

  async function toggleMuteState(tabId) {
    const tab = await chrome.tabs.get(tabId);
    const muted = !tab.mutedInfo.muted;
    await chrome.tabs.update(tabId, {muted});
    console.log(`Tab <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mrow><mi>t</mi><mi>a</mi><mi>b</mi><mi mathvariant="normal">.</mi><mi>i</mi><mi>d</mi></mrow><mi>i</mi><mi>s</mi></mrow><annotation encoding="application/x-tex">{tab.id} is </annotation></semantics></math></span><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.6944em;"></span><span class="mord"><span class="mord mathnormal">t</span><span class="mord mathnormal">ab</span><span class="mord">.</span><span class="mord mathnormal">i</span><span class="mord mathnormal">d</span></span><span class="mord mathnormal">i</span><span class="mord mathnormal">s</span></span></span></span>{muted ? "muted" : "unmuted"}`);
  }
  function toggleMuteState(tabId) {
    chrome.tabs.get(tabId, async (tab) => {
      let muted = !tab.mutedInfo.muted;
      await chrome.tabs.update(tabId, { muted });
      console.log(`Tab <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mrow><mi>t</mi><mi>a</mi><mi>b</mi><mi mathvariant="normal">.</mi><mi>i</mi><mi>d</mi></mrow><mi>i</mi><mi>s</mi></mrow><annotation encoding="application/x-tex">{tab.id} is </annotation></semantics></math></span><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.6944em;"></span><span class="mord"><span class="mord mathnormal">t</span><span class="mord mathnormal">ab</span><span class="mord">.</span><span class="mord mathnormal">i</span><span class="mord mathnormal">d</span></span><span class="mord mathnormal">i</span><span class="mord mathnormal">s</span></span></span></span>{ muted ? "muted" : "unmuted" }`);
    });
  }

Move the current tab to the first position when clicked

This example shows how to move a tab while a drag may or may not be in progress. While this example uses chrome.tabs.move, you can use the same waiting pattern for other calls that modify tabs while a drag is in progress.

  chrome.tabs.onActivated.addListener(moveToFirstPosition);

  async function moveToFirstPosition(activeInfo) {
    try {
      await chrome.tabs.move(activeInfo.tabId, {index: 0});
      console.log("Success.");
    } catch (error) {
      if (error == "Error: Tabs cannot be edited right now (user may be dragging a tab).") {
        setTimeout(() => moveToFirstPosition(activeInfo), 50);
      } else {
        console.error(error);
      }
    }
  }
  chrome.tabs.onActivated.addListener(moveToFirstPositionMV2);

  function moveToFirstPositionMV2(activeInfo) {
    chrome.tabs.move(activeInfo.tabId, { index: 0 }, () => {
      if (chrome.runtime.lastError) {
        const error = chrome.runtime.lastError;
        if (error == "Error: Tabs cannot be edited right now (user may be dragging a tab).") {
          setTimeout(() => moveToFirstPositionMV2(activeInfo), 50);
        } else {
          console.error(error);
        }
      } else {
        console.log("Success.");
      }
    });
  }

Pass a message to a selected tab's content script

This example demonstrates how an extension's service worker can communicate with content scripts in specific browser tabs using tabs.sendMessage().

function sendMessageToActiveTab(message) {
  const [tab] = await chrome.tabs.query({ active: true, lastFocusedWindow: true });
  const response = await chrome.tabs.sendMessage(tab.id, message);
  // TODO: Do something with the response.
}

Extension examples

For more Tabs API extensions demos, explore any of the following:

Types

MutedInfo

The tab's muted state and the reason for the last state change.

Properties

MutedInfoReason

An event that caused a muted state change.

Enum

"user"
A user input action set the muted state.

"capture"
Tab capture was started, forcing a muted state change.

"extension"
An extension, identified by the extensionId field, set the muted state.

Tab

Properties

TabStatus

The tab's loading status.

Enum

"unloaded"

"loading"

"complete"

WindowType

The type of window.

Enum

"normal"

"popup"

"panel"

"app"

"devtools"

ZoomSettings

Defines how zoom changes in a tab are handled and at what scope.

Properties

ZoomSettingsMode

Defines how zoom changes are handled, i.e., which entity is responsible for the actual scaling of the page; defaults to automatic.

Enum

"automatic"
Zoom changes are handled automatically by the browser.

"manual"
Overrides the automatic handling of zoom changes. The onZoomChange event will still be dispatched, and it is the extension's responsibility to listen for this event and manually scale the page. This mode does not support per-origin zooming, and thus ignores the scope zoom setting and assumes per-tab.

"disabled"
Disables all zooming in the tab. The tab reverts to the default zoom level, and all attempted zoom changes are ignored.

ZoomSettingsScope

Defines whether zoom changes persist for the page's origin, or only take effect in this tab; defaults to per-origin when in automatic mode, and per-tab otherwise.

Enum

"per-origin"
Zoom changes persist in the zoomed page's origin, i.e., all other tabs navigated to that same origin are zoomed as well. Moreover, per-origin zoom changes are saved with the origin, meaning that when navigating to other pages in the same origin, they are all zoomed to the same zoom factor. The per-origin scope is only available in the automatic mode.

"per-tab"
Zoom changes only take effect in this tab, and zoom changes in other tabs do not affect the zooming of this tab. Also, per-tab zoom changes are reset on navigation; navigating a tab always loads pages with their per-origin zoom factors.

Properties

MAX_CAPTURE_VISIBLE_TAB_CALLS_PER_SECOND

The maximum number of times that captureVisibleTab can be called per second. captureVisibleTab is expensive and should not be called too often.

SPLIT_VIEW_ID_NONE

An ID that represents the absence of a split tab.

TAB_ID_NONE

An ID that represents the absence of a browser tab.

TAB_INDEX_NONE

An index that represents the absence of a tab index in a tab_strip.

Methods

captureVisibleTab()

chrome.tabs.captureVisibleTab(
  windowId?: number,
  options?: ImageDetails,
): Promise

Captures the visible area of the currently active tab in the specified window. In order to call this method, the extension must have either the <all_urls> permission or the activeTab permission. In addition to sites that extensions can normally access, this method allows extensions to capture sensitive sites that are otherwise restricted, including chrome:-scheme pages, other extensions' pages, and data: URLs. These sensitive sites can only be captured with the activeTab permission. File URLs may be captured only if the extension has been granted file access.

Returns

connect()

chrome.tabs.connect(
  tabId: number,
  connectInfo?: object,
): runtime.Port

Connects to the content script(s) in the specified tab. The runtime.onConnect event is fired in each content script running in the specified tab for the current extension. For more details, see Content Script Messaging.

Parameters

Returns

create()

chrome.tabs.create(
  createProperties: object,
): Promise<Tab>

Creates a new tab.

Parameters

Returns

detectLanguage()

chrome.tabs.detectLanguage(
  tabId?: number,
): Promise

Detects the primary language of the content in a tab.

Returns

discard()

chrome.tabs.discard(
  tabId?: number,
): Promise<Tab | undefined>

Discards a tab from memory. Discarded tabs are still visible on the tab strip and are reloaded when activated.

Parameters

Returns

duplicate()

chrome.tabs.duplicate(
  tabId: number,
): Promise<Tab | undefined>

Duplicates a tab.

Parameters

Returns

get()

chrome.tabs.get(
  tabId: number,
): Promise<Tab>

Retrieves details about the specified tab.

Parameters

Returns

getCurrent()

chrome.tabs.getCurrent(): Promise<Tab | undefined>

Gets the tab that this script call is being made from. Returns undefined if called from a non-tab context (for example, a background page or popup view).

Returns

getZoom()

chrome.tabs.getZoom(
  tabId?: number,
): Promise

Gets the current zoom factor of a specified tab.

Parameters

Returns

getZoomSettings()

chrome.tabs.getZoomSettings(
  tabId?: number,
): Promise<ZoomSettings>

Gets the current zoom settings of a specified tab.

Parameters

Returns

goBack()

chrome.tabs.goBack(
  tabId?: number,
): Promise

Go back to the previous page, if one is available.

Parameters

Returns

goForward()

chrome.tabs.goForward(
  tabId?: number,
): Promise

Go foward to the next page, if one is available.

Parameters

Returns

group()

chrome.tabs.group(
  options: object,
): Promise

Adds one or more tabs to a specified group, or if no group is specified, adds the given tabs to a newly created group.

Parameters

Returns

highlight()

chrome.tabs.highlight(
  highlightInfo: object,
): Promise<windows.Window>

Highlights the given tabs and focuses on the first of group. Will appear to do nothing if the specified tab is currently active.

Parameters

Returns

move()

chrome.tabs.move(
  tabIds: number | number[],
  moveProperties: object,
): Promise<Tab | Tab[]>

Moves one or more tabs to a new position within its window, or to a new window. Note that tabs can only be moved to and from normal (window.type === "normal") windows.

Parameters

Returns

query()

chrome.tabs.query(
  queryInfo: object,
): Promise<Tab[]>

Gets all tabs that have the specified properties, or all tabs if no properties are specified.

Parameters

Returns

reload()

chrome.tabs.reload(
  tabId?: number,
  reloadProperties?: object,
): Promise

Reload a tab.

Parameters

Returns

remove()

chrome.tabs.remove(
  tabIds: number | number[],
): Promise

Closes one or more tabs.

Parameters

Returns

sendMessage()

chrome.tabs.sendMessage(
  tabId: number,
  message: any,
  options?: object,
): Promise

Sends a single message to the content script(s) in the specified tab, with an optional callback to run when a response is sent back. The runtime.onMessage event is fired in each content script running in the specified tab for the current extension.

Parameters

Returns

setZoom()

chrome.tabs.setZoom(
  tabId?: number,
  zoomFactor: number,
): Promise

Zooms a specified tab.

Parameters

Returns

setZoomSettings()

chrome.tabs.setZoomSettings(
  tabId?: number,
  zoomSettings: ZoomSettings,
): Promise

Sets the zoom settings for a specified tab, which define how zoom changes are handled. These settings are reset to defaults upon navigating the tab.

Parameters

Returns

ungroup()

chrome.tabs.ungroup(
  tabIds: number | [number, ...number[]],
): Promise

Removes one or more tabs from their respective groups. If any groups become empty, they are deleted.

Parameters

Returns

update()

chrome.tabs.update(
  tabId?: number,
  updateProperties: object,
): Promise<Tab | undefined>

Modifies the properties of a tab. Properties that are not specified in updateProperties are not modified.

Parameters

Returns

Events

onActivated

chrome.tabs.onActivated.addListener(
  callback: function,
)

Fires when the active tab in a window changes. Note that the tab's URL may not be set at the time this event fired, but you can listen to onUpdated events so as to be notified when a URL is set.

Parameters

onAttached

chrome.tabs.onAttached.addListener(
  callback: function,
)

Fired when a tab is attached to a window; for example, because it was moved between windows.

Parameters

onCreated

chrome.tabs.onCreated.addListener(
  callback: function,
)

Fired when a tab is created. Note that the tab's URL and tab group membership may not be set at the time this event is fired, but you can listen to onUpdated events so as to be notified when a URL is set or the tab is added to a tab group.

Parameters

onDetached

chrome.tabs.onDetached.addListener(
  callback: function,
)

Fired when a tab is detached from a window; for example, because it was moved between windows.

Parameters

onHighlighted

chrome.tabs.onHighlighted.addListener(
  callback: function,
)

Fired when the highlighted or selected tabs in a window changes.

Parameters

onMoved

chrome.tabs.onMoved.addListener(
  callback: function,
)

Fired when a tab is moved within a window. Only one move event is fired, representing the tab the user directly moved. Move events are not fired for the other tabs that must move in response to the manually-moved tab. This event is not fired when a tab is moved between windows; for details, see tabs.onDetached.

Parameters

onRemoved

chrome.tabs.onRemoved.addListener(
  callback: function,
)

Fired when a tab is closed.

Parameters

onReplaced

chrome.tabs.onReplaced.addListener(
  callback: function,
)

Fired when a tab is replaced with another tab due to prerendering or instant.

Parameters

onUpdated

chrome.tabs.onUpdated.addListener(
  callback: function,
)

Fired when a tab is updated.

Parameters

onZoomChange

chrome.tabs.onZoomChange.addListener(
  callback: function,
)

Fired when a tab is zoomed.

Parameters

Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. For details, see the Google Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.

Last updated 2025-12-12 UTC.