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.
Overview
The Tabs API not only offers features for manipulating and managing tabs, but can also detect the language of the tab, take a screenshot, and communicate with a tab's content scripts.
Permissions
Most features do not 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.tabsnamespace. Instead, it grants an extension the ability to calltabs.query()against four sensitive properties ontabs.Tabinstances:url,pendingUrl,title, andfavIconUrl. - Host permissions
- Host permissions allow an extension to read and query a matching tab's four sensitive
tabs.Tabproperties. They can also interact directly with the matching tabs using methods such astabs.captureVisibleTab(),tabs.executeScript(),tabs.insertCSS(), andtabs.removeCSS(). - The "activeTab" permission
activeTabgrants an extension temporary host permission for the current tab in response to a user invocation. Unlike host permissions,activeTabdoes not trigger any warnings.
Manifest
The following are examples of how to declare each permission in the manifest:
{
"name": "My extension",
...
"permissions": [
"tabs"
],
...
}
{
"name": "My extension",
...
"host_permissions": [
"http://*/*",
"https://*/*"
],
...
}
{
"name": "My extension",
...
"permissions": [
"activeTab"
],
...
}
Use cases
The following sections demonstrate some common use cases.
Opening 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]