chrome.storage
chrome.storage 是擴充功能專用的資料儲存 API,取代網頁常見的 localStorage。它是非同步的,所有元件(Background、Content Script、Popup、Options)都能存取同一份資料,是串連各元件狀態的核心工具,見 訊息傳遞 中的範例。
local、sync、session 三種儲存區
| 儲存區 | 特性 | 容量 | 適合存放 |
|---|---|---|---|
chrome.storage.local |
只存在使用者這台裝置 | 約數 MB(可宣告 unlimitedStorage 放寬) |
快取、較大的資料 |
chrome.storage.sync |
會透過使用者的 Google 帳號同步到其他登入裝置 | 每個項目 8KB、總量約 100KB | 使用者偏好設定 |
chrome.storage.session |
只存在記憶體,瀏覽器關閉即清空 | 約數 MB | 不需要跨瀏覽器工作階段保留的暫存資料 |
localStorage 只有 Content Script 能用、無法跨元件共用,且是同步 API 會阻塞執行緒,因此 Chrome Extension 開發一律建議用 chrome.storage 取代。
基本讀寫
// 寫入
chrome.storage.local.set({ theme: "dark", noteCount: 3 });
// 讀取單一或多個 key
chrome.storage.local.get(["theme", "noteCount"], (result) => {
console.log(result.theme, result.noteCount);
});
// 讀取全部資料
chrome.storage.local.get(null, (allData) => {
console.log(allData);
});
// 刪除
chrome.storage.local.remove("noteCount");
在 Manifest V3 的環境(Background Service Worker、Popup 等)中,這些方法也都支援 async/await:
const { theme } = await chrome.storage.local.get("theme");
await chrome.storage.local.set({ theme: "light" });
監聽資料變化:onChanged
當 Popup 顯示的資料是由 Background 更新的,可以監聽 onChanged 即時反應,不需要輪詢:
chrome.storage.onChanged.addListener((changes, areaName) => {
if (areaName === "local" && changes.noteCount) {
console.log("舊值:", changes.noteCount.oldValue);
console.log("新值:", changes.noteCount.newValue);
}
});
使用要點
- 先在
manifest.json加入"permissions": ["storage"],否則chrome.storage會是undefined。 sync的容量限制很小(單一項目 8KB),儲存大量資料一律用local。- 讀寫都是非同步的,務必用回呼或
await取得結果,不要假設set呼叫後資料立刻可讀。
下一步
接著看 chrome.tabs 與 chrome.scripting,學習如何取得分頁資訊、動態注入程式碼。