[英]Session for each tab - Google Chrome Extension
在 Google Chrome 擴展程序中,是否可以為每個選項卡設置不同的“會話”?
例如,Adblock 就是這樣做的:它顯示當前頁面被阻止的廣告數量,每個標簽的數量都會發生變化(如果您打開了 2 個窗口,每個窗口的數量不同......)
例如,如果我使用 Chrome 演示更改單擊圖標:
清單文件
{
"name": "A browser action which changes its icon when clicked",
"description": "Change browser action color when its icon is clicked",
"version": "1.2",
"background": { "scripts": ["background.js"] },
"browser_action": {
"name": "Click to change the icon's color"
},
"manifest_version": 2
}
背景.js
var min = 1;
var max = 5;
var current = min;
function updateIcon() {
chrome.browserAction.setIcon({path:"icon" + current + ".png"});
current++;
if (current > max)
current = min;
}
chrome.browserAction.onClicked.addListener(updateIcon);
updateIcon();
有沒有辦法添加一些代碼以在每個選項卡上具有不同的“范圍”? 例如,如果我在第一個選項卡上單擊 3 次,它會顯示 icon3,如果我打開一個新選項卡,它會顯示該選項卡的 icon1(但第一個選項卡仍然是 icon3)
謝謝
chrome.browserAction
API通過提供並采用tabId
作為參數來考慮選項卡。
例如,這是一個onClicked
偵聽器的預期簽名:
回調參數應該是一個如下所示的函數:
function( tabs.Tab tab) {...};
tabs.Tab
tab
因此,在您的updateIcon
函數中,您可以獲得選項卡的 ID:
function updateIcon(tab) {
// Can use tab.id here
/* ... */
chrome.browserAction.setIcon({
path:"icon" + current + ".png",
tabId: tab.id // Limit change to tab
});
}
當然,這意味着您必須按標簽存儲數據。 最簡單的方法是使current
對象(或數組,但它會是稀疏的)與tabId
s 充當鍵。
var min = 1;
var max = 5;
var current = {};
function updateIcon(tab) {
if (!current[tab.id]) { // Not yet defined
current[tab.id] = min;
}
chrome.browserAction.setIcon({
path: "icon" + current[tab.id] + ".png",
tabId: tab.id
});
if (current[tab.id] === max) {
current[tab.id] = min;
} else {
current[tab.id]++;
}
}
如果您擔心標簽數據隨着時間的推移而增長,您可以收聽chrome.tabs.onRemoved
來清除數據。
您可能還需要注意chrome.tabs.onReplaced
(它替換選項卡內的內容,更改 ID)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.