我正在嘗試將 Chrome 擴展程式切換為使用 Manifest v3。
除了我正在使用的地方,我已經得到了一切localStorage:
if (localStorage.getItem(lastchecked[0]) < Date.now() - 2500000000) {
localStorage.setItem(lastchecked[0], Date.now());
} else {
const remover = Date.now() - 2500000000;
Object.entries(localStorage).forEach(([k, v]) => {
if (v < remover) {
delete localStorage[k];
}
});
}
這是我得到的錯誤:
ReferenceError: localStorage is not defined
從我所知道的,這是因為我使用背景切換擴展script到使用service worker,這似乎并沒有給進入localStorage。
除了localStorage因為它不可用之外,還有什么簡單的方法可以將其切換為使用其他東西嗎?
uj5u.com熱心網友回復:
localStorage根據規范在服務作業者中不可用。原因是因為它提供同步訪問,所以必須在啟動 JS 環境之前完整讀取它,這可能需要一些時間,這與環境本身的啟動時間(~50ms)相當,以防存盤包含幾兆位元組(最大為 5MB)。
Service Worker 中只有異步存盤 API 可用。
擴展可以使用這些:
chrome.storage
- 好:少量簡單資料
- 好:直接在內容腳本中可用
- meh:僅與 JSON 兼容的型別(字串、數字、布林值、null、物件/陣列遞回地由這些型別組成),因此嘗試存盤復雜的事物,例如
SetorMap將最終作為空物件{},您必須將它們序列化,例如[...mySet]寫的new Set(result.foo)時候,讀的時候。 - 不好:大/嵌套資料非常慢
索引資料庫
- 好:對于任何數量/復雜性的資料都非常快
- 好:更多資料型別,如 ArrayBuffer、File、Blob、型別化陣列、Set、Map,
請參閱結構化克隆演算法 - meh:資料在內容腳本中不可用,因此您必須使用訊息傳遞
- 不好:它的 API 過時且笨拙,但有幾個庫可以修復它
這些 API 是異步的,因此您必須重新撰寫代碼。
由于 Chrome 95 promisified chrome.storage,我們可以使用 async/await 作為您的示例。
并且不要忘記在 manifest.json 中"storage"添加"permissions"。
const LS = chrome.storage.local;
async function pruneStorage() {
const remover = Date.now() - 2500000000;
const key = lastchecked[0];
if ((await LS.get(key))[key] < remover) {
await LS.set({[key]: Date.now()});
} else {
const toRemove = Object.entries(await LS.get())
.map(([k, v]) => v < remover && k)
.filter(Boolean);
if (toRemove.length) {
await LS.remove(toRemove);
}
}
}
或者,模仿localStorage:
const LS = {
getAllItems: () => chrome.storage.local.get(),
getItem: async key => (await chrome.storage.local.get(key))[key],
setItem: (key, val) => chrome.storage.local.set({[key]: val}),
removeItems: keys => chrome.storage.local.remove(keys),
};
async function pruneStorage() {
const remover = Date.now() - 2500000000;
const key = lastchecked[0];
if (await LS.getItem(key) < remover) {
await LS.setItem(key, Date.now());
} else {
const toRemove = Object.entries(await LS.getAllItems())
.map(([k, v]) => v < remover && k)
.filter(Boolean);
if (toRemove.length) {
await LS.removeItems(toRemove);
}
}
}
async警告:如果您想異步發送回應,請不要讓您的 chrome.runtime.onMessage 偵聽器,請改用異步 IIFE 或單獨的函式,更多資訊。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/413062.html
標籤:
