谷歌Chrome扩展程序如何检查存储是否为空?

时间:2017-04-06 09:38:47

标签: javascript google-chrome-extension storage google-chrome-storage

如何检查我的Google Chrome扩展程序中的存储空是否为空?我尝试了很多可能性,但对我没什么用。

1 个答案:

答案 0 :(得分: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);