Google chrome 扩展程序如何检查存储是否为空?

Google chrome extension how to check if storage is empty?

如何检查我的 google chrome 扩展中的存储空间是否为空?我尝试了很多可能性,但没有任何效果。

这很简单。

要获取当前正在使用的存储字节数,您可以使用 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 参数接受一个字符串数组或单个字符串,每个字符串代表存储您希望计算字节数的数据的键。

如果您的扩展没有使用任何 space(空),您将使用零字节。

可以在 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);