storage.local

代表 local 儲存空間。通常 local 裡面的東西,會放在套件安裝的地方。

瀏覽器可能會限制套件本地可儲存的資料數量:

  • Chrome 限制套件內用到此 API 資料的上限為 5MB,除非有 unlimitedStorage 權限。
  • 56 版以後的 Firefox 將能要求 unlimitedStorage 權限。目前 Firefox 還沒有限制套件內的資料上限,但這功能會在未來引入:因此,如果可能會儲存大容量的資料,最好要實做 unlimitedStorage 的請求。

如果套件被移除、相關的儲存資料也會一併移除。

在 Firefox 內,你可以透過 about:config 內設定 keepUuidOnUninstall 與 keepStorageOnUninstall 為 true 以避免瀏覽器在移除套件時,一併移除相關的儲存資料。這個功能是為了方便開發者除錯,套件本身無法改變這個設定。

雖然這 API 與 Window.localStorage 相似,但不建議在套件內使用 Window.localStorage。在某些情況下,用戶會出於隱私上的理由,要求 Firefox 清理瀏覽紀錄與資料,這其中就包含使用 localStorage API 的資料。另一方面,storage.local API 的資料,在這種情況下會予以保留。

方法

local 物件實做了定義於 storage.StorageArea 類別的方法:

storage.StorageArea.get()

取得一個或多個源自儲存空間的項目。

storage.StorageArea.getBytesInUse()

取得儲存空間內,一個或多個已為項目所使用的容量。單位為 byte。

storage.StorageArea.set()

Stores one or more items in the storage area. If the item already exists, its value will be updated. When you set a value, the storage.onChanged event will fire.

storage.StorageArea.remove()

刪除一個或多個儲存空間內的項目。

storage.StorageArea.clear()

刪除所有儲存空間內的項目。

瀏覽器相容性

範例擴充套件

備註: 此 API 基於 Chromium 的 chrome.storage API 而來,文件改作自 Chromium 程式碼裡的 storage.json