0

如何檢查我的google chrome擴展程序中的存儲是否爲空?我嘗試了很多可能性,但沒有爲我工作。谷歌Chrome擴展如何檢查存儲是否爲空?

+1

使用'null' [ .get](https://developer.chrome.com/extensions/storage#method-StorageArea-get),然後用Object.keys對結果中的鍵進行計數。 – wOxxOm

回答

1

這很簡單。

要獲得當前正在使用的存儲字節數,可以使用chrome.storage API。

如果您將擴展詳細信息存儲在名爲'settings'的對象中,則可以通過以下方式檢索正在使用的字節數。

function logBytes(bytes) { 
    console.log(bytes); 
} 

// gets the number of bytes used in sync storage area 
chrome.storage.sync.getBytesInUse(['settings'], logBytes); 

// gets the number of bytes used in the local storage area 
chrome.storage.local.getBytesInUse(['settings'], logBytes]); 

的getBytesInUse參數採用一個字符串數組或一個字符串,表示存儲數據的要計數的字節的按鍵的每個字符串。

如果您的擴展沒有使用任何空格(空),您將使用零字節。

更多文檔,Chrome Storage API

擴展在wOxxOm的評論可以發現,你可以在存儲通過執行以下保持的當前對象:在鍵名

function logBytes(bytes) { 
    console.log(bytes); 
} 

function getSyncBytes(settings) { 
    var keys = Object.keys(settings); 
    chrome.storage.sync.getBytesInUse(keys, logBytes); 
} 

function getLocalBytes(settings) { 
    var keys = Object.keys(settings); 
    chrome.storage.local.getBytesInUse(keys, logBytes); 
} 

chrome.storage.sync.get(null, getSyncBytes); 
chrome.storage.local.get(null, getLocalBytes); 
+0

非常感謝!你不相信我正在研究這個問題多久了! – Doppler

+0

@多普勒不是問題!我只是擴展了答案,展示瞭如何通過擴展wOxxOm的評論來獲得擴展使用的所有空間。 –