我們在 Day 19 的時候有提到透過 chrome.tabs.sendMessage
API來傳送資料
今天我們來詳細 Tabs API 介紹吧!
在多分頁情境下,我們常常需要「知道使用者正在看哪一個分頁」或「讓 content script 在目前頁面做事」。這時候就會需要使用 Tabs API
chrome.tabs
提供了許多跟瀏覽器「分頁(tab)」有關的功能:
{
"name": "My extension",
...
"permissions": [
"tabs"
],
...
}
chrome.tabs.create
chrome.runtime.onInstalled.addListener(({reason}) => {
if (reason === 'install') {
chrome.tabs.create({
url: "onboarding.html"
});
}
});
chrome.tabs.query(queryInfo, callback)
chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
const activeTab = tabs[0];
console.log("目前作用中的分頁:", activeTab);
});
chrome.tabs.update(tabId, {muted})
//方法一
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"}`);
}
//方法二
function toggleMuteState(tabId) {
chrome.tabs.get(tabId, async (tab) => {
let muted = !tab.mutedInfo.muted;
await chrome.tabs.update(tabId, { muted });
console.log(`Tab ${tab.id} is ${ muted ? "muted" : "unmuted" }`);
});
}
chrome.tabs.move
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.sendMessage(tabId, message, responseCallback?)
chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
chrome.tabs.sendMessage(tabs[0].id, { action: "getMRTitle" }, (response) => {
console.log("收到 MR 標題:", response.title);
});
});
chrome.runtime.sendMessage
vs. chrome.tabs.sendMessage
chrome.runtime.sendMessage
chrome.tabs.sendMessage