跳到主要内容

tabs 选项卡

官方文档

提供用于操作和管理选项卡的功能,还可以检测选项卡的语言、截取屏幕截图以及与选项卡的内容脚本进行通信。

权限设置

"permissions": [
"tabs",
"activeTab"
],
"host_permissions": [
"tabs"
]
提示

大多数功能不需要任何权限即可使用。例如:创建新选项卡、重新加载选项卡、导航到另一个 URL 等。

方法 - 创建

create() 创建选项卡

type MutedInfoReason = 'user' | 'capture' | 'extension';
type MutedInfo = {
// 更改静音状态的扩展的 ID。如果扩展不是上次静音状态更改的原因,则不设置。
extensionId: string;
// 选项卡是否静音(阻止播放声音)。即使尚未播放或当前未播放声音,选项卡也可能被静音。等同于是否显示“静音”音频指示器。
muted: boolean;
// 更改静音状态的原因。如果选项卡的静音状态从未更改过,则不设置。
reason: MutedInfoReason;
}
type TabStatus = 'unloaded' | 'loading' | 'complete';
type Tab = {
// 选项卡在其窗口中是否处于活动状态。并不一定意味着窗口是聚焦的。
active: boolean;
// 是否非静音
audible?: boolean;
// 当资源不足时,浏览器是否可以自动丢弃选项卡
autoDiscardable:boolean;
// 是否丢弃选项卡。丢弃的选项卡是指其内容已从内存中卸载,但在选项卡条中仍然可见的选项卡。下次激活时会重新加载其内容。
discarded: boolean;
// 选项卡的图标的 URL。仅当扩展的清单包含 "tabs" 权限时,此属性才存在。如果选项卡正在加载,它也可能是一个空字符串。
favIconUrl?: string;
// 选项卡所属组的 ID。
groupId: number;
// 选项卡的高度(以像素为单位)。
height: number;
// 选项卡是否突出显示。
highlighted: boolean;
// 选项卡的 ID。选项卡 ID 在浏览器会话中是唯一的。在某些情况下,可能不会为选项卡分配 ID;例如,使用 sessions API 查询外部选项卡时,在这种情况下,可能存在会话 ID。还可以为 chrome.tabs.TAB_ID_NONE 应用和开发工具窗口设置选项卡 ID。
id?: number;
// 选项卡是否位于隐身窗口中。
incognito: boolean;
// 选项卡在其窗口中的从零开始的索引。
index: number;
// 选项卡的静音状态以及上次状态更改的原因。
mutedInfo?: MutedInfo;
// 打开此选项卡的选项卡的 ID(如果有)。仅当打开程序选项卡仍然存在时,此属性才存在。
openerTabId?: number;
// 选项卡在提交之前导航到的 URL。仅当扩展的清单包含 "tabs" 权限并且存在挂起的导航时,此属性才存在。
pendingUrl?: string;
// 选项卡是否固定。
pinned: boolean;
// 是否选择选项卡
selected: boolean;
// 选项卡的会话 ID。会话 ID 在浏览器会话中是唯一的。
sessionId?: string;
// 选项卡的loading状态。
status?: TabStatus;
// 选项卡的标题。
title?: string;
// 选项卡主框架的最后提交的 URL。仅当扩展的清单包含 "tabs" 权限时,此属性才存在,如果选项卡尚未提交,则此属性可能为空字符串
url?: string;
// 选项卡的宽度(以像素为单位)。
width?: number;
// 选项卡所属的窗口的 ID。
windowId: number;
}
type CreateProperties = {
// 选项卡是否应处于活动状态。如果未指定,则选项卡默认处于活动状态。
active?: boolean;
// 选项卡的索引,以零为基数,其中0是窗口中的第一个选项卡。如果未指定,则将选项卡添加到窗口的末尾。
index?: number;
// 选项卡的ID。如果指定了该属性,则将其作为新选项卡的父选项卡。
openerTabId?: number;
// 选项卡是否应处于固定状态。如果未指定,则选项卡将不固定。
pinned?: boolean;
selected?: boolean;
// 要加载的 URL。如果未指定,则将加载“新标签页”。
url?: string;
// 选项卡的父窗口ID。如果未指定,则使用当前选项卡的窗口。
windowId: number;
}
chrome.tabs.create(
createProperties: CreateProperties,
callback?: (tab: Tab) => void,
)
// background.js
// 在安装扩展时在新选项卡中打开载入页面
chrome.runtime.onInstalled.addListener(({reason}) => {
if (reason === 'install') {
chrome.tabs.create({
url: "onboarding.html"
});
}
});

方法 - 获取

query() 获取指定选项卡

type WindowType = 'normal' | 'popup' | 'panel' | 'app' | 'devtools';
type QueryInfo = {
// 选项卡是否应处于活动状态。如果未指定,则选项卡默认处于活动状态。
active?: boolean;
// 选项卡是否在当前窗口中
currentWindow?: boolean;
// 选项卡是否位于最后一个焦点窗口中
lastFocusedWindow?: boolean;

// 是否非静音
audible?: boolean;
// 当资源不足时,浏览器是否可以自动丢弃选项卡
autoDiscardable?:boolean;
// 是否丢弃选项卡。丢弃的选项卡是指其内容已从内存中卸载,但在选项卡条中仍然可见的选项卡。下次激活时会重新加载其内容。
discarded?: boolean;
// 选项卡是否突出显示。
highlighted?: boolean;
// 选项卡是否静音
muted?: number;
// 选项卡是否应处于固定状态。如果未指定,则选项卡将不固定。
pinned?: boolean;

// 选项卡的索引,以零为基数,其中0是窗口中的第一个选项卡。如果未指定,则将选项卡添加到窗口的末尾。
index?: number;
// 选项卡的标题。
title?: string;
// 要加载的 URL。如果未指定,则将加载“新标签页”。
url?: string;
// 选项卡的loading状态。
status?: TabStatus;

// 选项卡所属组的 ID。
groupId?: number;
// 选项卡的父窗口ID。如果未指定,则使用当前选项卡的窗口。
windowId?: number;
windowType?: WindowType
}
chrome.tabs.query(
queryInfo: QueryInfo,
callback?: (result: Tab[]) => void,
)

get() 根据tabId获取选项卡

chrome.tabs.get(
tabId: number,
callback?: (result: Tab[]) => void,
)

getCurrent() content中获取当前选项卡

获取从中进行此脚本调用的选项卡。如果从非选项卡上下文(例如,背景页面或弹出视图)调用,则返回 undefined

chrome.tabs.getCurrent(
callback?: (tab: Tab) => void,
)

方法 - 更新

update() 修改选项卡

type UpdateProperties = {
// 选项卡是否应处于活动状态。如果未指定,则选项卡默认处于活动状态。
active?: boolean;
// 当资源不足时,浏览器是否可以自动丢弃选项卡
autoDiscardable?:boolean;
// 选项卡是否突出显示。
highlighted?: boolean;
// 选项卡是否静音
muted?: number;
// 选项卡是否应处于固定状态。如果未指定,则选项卡将不固定。
pinned?: boolean;
// 打开此选项卡的选项卡的 ID(如果有)。仅当打开程序选项卡仍然存在时,此属性才存在。
openerTabId?: number;
}
chrome.tabs.update(
tabId?: number,
updateProperties: UpdateProperties,
callback?: (tab: Tab) => void,
)

move() 移动选项卡

type MoveProperties = {
// 要将窗口移动到的位置。用于 -1 将选项卡放置在窗口末尾。
index: number;
// 默认设置为选项卡当前所在的窗口。
windowId?: number;
}
chrome.tabs.move(
tabIds: number | number[],
moveProperties: MoveProperties,
callback?: (tab: Tab) => void,
)

duplicate() 复制选项卡

chrome.tabs.duplicate(
tabId?: number,
callback?: (tab: Tab) => void,
)

reload() 重新加载选项卡

type ReloadProperties = {
// 是否跳过缓存
bypassCache?: boolean;
}
chrome.tabs.reload(
tabId?: number,
reloadProperties?: ReloadProperties,
callback?: () => void,
)

goBack() 返回上一页

chrome.tabs.goBack(
tabId?: number,
callback?: () => void,
)

goForward() 前进一页

chrome.tabs.goForward(
tabId?: number,
callback?: () => void,
)

remove() 关闭选项卡

chrome.tabs.remove(
tabIds: number | number[],
callback?: () => void,
)

group() 将选项卡添加到组

type GroupOptions = {
windowId?: number;
groupId?: number;
tabIds: number | [number,...number[]],
}
chrome.tabs.group(
options: GroupOptions,
callback?: (groupId: number) => void,
)

ungroup() 将选项卡从组中移除

chrome.tabs.ungroup(
tabIds: number | [number,...number[]],
callback?: () => void,
)

方法 - 消息传递

sendMessage() 向content发送消息

向指定选项卡中的内容脚本发送一条消息,并在发送回响应时运行可选回调

type Message = any;
chrome.tabs.sendMessage(
tabId: number,
message: Message,
options?: {
documentId?: string;
frameId?: number;
},
responseCallback?: (response: Message) => void,
)

方法 - 属性获取与更新

captureVisibleTab() 获取可见区域

捕获指定窗口中当前活动选项卡的可见区域

type ImageFormat = 'jpeg' | 'png';
type CaptureVisibleTabOptions = {
// 指定图像格式的字符串。默认为“png”。
format?: ImageFormat;
// 指定图像质量的数字。从0到100的范围内。默认为100。
quality?: number;
}
chrome.tabs.captureVisibleTab(
windowId?: number,
options?: CaptureVisibleTabOptions,
callback?: (dataUrl: string) => void,
)

detectLanguage() 检测语言

chrome.tabs.detectLanguage(
tabId?: number,
callback?: (language: string) => void,
)

discard() 丢弃选项卡

chrome.tabs.discard(
tabId?: number,
callback?: (tab?: Tab) => void,
)

highlight() 高亮选项卡

type HighlightInfo = {
// 选项卡的 ID。
tabs: number[];
// 选项卡所属的窗口的 ID。
windowId?: number;
}


### getZoom() 获取缩放比例

```ts
chrome.tabs.getZoom(
tabId?: number,
callback?: (zoomFactor: number) => void,
)

getZoomSettings() 获取缩放设置

type ZoomSettings = {
defaultZoomFactor: number;
// 是否允许缩放
mode: 'automatic' | 'manual' | 'disabled';
// 缩放比例
scope: 'per-origin' | 'per-tab';
}
chrome.tabs.getZoomSettings(
tabId?: number,
callback?: (zoomSettings: ZoomSettings) => void,
)

setZoom() 设置缩放比例

chrome.tabs.setZoom(
tabId?: number,
zoomFactor: number,
callback?: () => void,
)

setZoomSettings() 设置缩放设置

type ZoomSettings = {
defaultZoomFactor: number;
// 是否允许缩放
mode: 'automatic' | 'manual' | 'disabled';
// 缩放比例
scope: 'per-origin' | 'per-tab';
}
chrome.tabs.setZoomSettings(
tabId?: number,
zoomSettings: ZoomSettings,
callback?: () => void,
)

事件

onCreated() 选项卡创建时触发

chrome.tabs.onCreated.addListener(
callback: (tab: Tab) => void,
)

onUpdated() 选项卡更新时触发

chrome.tabs.onUpdated.addListener(
callback: (
tabId: number,
changeInfo: {
status?: TabStatus,
url?: string,
pinned?: boolean,
audible?: boolean,
discarded?: boolean,
autoDiscardable?: boolean,
mutedInfo?: MutedInfo,
favIconUrl?: string,
title?: string
},
tab: Tab
) => void,
)

onMoved() 选项卡移动时触发

chrome.tabs.onMoved.addListener(
callback: (
tabId: number,
moveInfo: {
fromIndex: number,
toIndex: number,
windowId: number
},
tab: Tab
) => void,
)

onActivated() 选项卡激活时触发

chrome.tabs.onActivated.addListener(
callback: (activeInfo: {tabId: number, windowId: number}) => void,
)

onHighlighted() 选项卡高亮时触发

chrome.tabs.onHighlighted.addListener(
callback: (highlightInfo: HighlightInfo) => void,
)

onDetached() 选项卡从窗口中分离时触发

chrome.tabs.onDetached.addListener(
callback: (tabId: number, detachInfo: {oldWindowId: number, oldPosition: number}) => void,
)

onAttached() 选项卡附加到窗口时触发

chrome.tabs.onAttached.addListener(
callback: (tabId: number, attachInfo: {newWindowId: number, newPosition: number}) => void,
)

onRemoved() 选项卡关闭时触发

chrome.tabs.onRemoved.addListener(
callback: (tabId: number, removeInfo: {windowId: number, isWindowClosing: boolean}) => void,
)

onReplaced() 选项卡替换时触发

chrome.tabs.onReplaced.addListener(
callback: (addedTabId: number, removedTabId: number) => void,
)

onZoomChange() 选项卡缩放时触发

chrome.tabs.onZoomChange.addListener(
callback: (ZoomChangeInfo: {tabId: number, oldZoomFactor: number, newZoomFactor: number, zoomSettings: ZoomSettings}) => void,
)

示例

获取当前选项卡

async function getCurrentTab() {
let queryOptions = { active: true, lastFocusedWindow: true };
// 或 let queryOptions = { active: true, currentWindow: true };
let [tab] = await chrome.tabs.query(queryOptions);
return 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 ${tab.id} is ${muted ? "muted" : "unmuted"}`);
}

单击时将当前选项卡移到第一个位置

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);
}
}
}