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的评论来获得扩展使用的所有空间。 –

相关问题