chrome.storage.sync.remove数组不起作用

ame*_*lon 4 javascript google-chrome-extension google-chrome-storage

我正在制作一个小型Chrome扩展程序.我想使用,chrome.storage但我无法从存储中删除多个项目(数组).单项删除有效.

function clearNotes(symbol)
{
    var toRemove = "{";

    chrome.storage.sync.get(function(Items) {
        $.each(Items, function(index, value) {
            toRemove += "'" + index + "',";         
        });
        if (toRemove.charAt(toRemove.length - 1) == ",") {
            toRemove = toRemove.slice(0,- 1);
        }
        toRemove = "}";
        alert(toRemove);
    });

    chrome.storage.sync.remove(toRemove, function(Items) {
        alert("removed");
        chrome.storage.sync.get( function(Items) {
            $.each(Items, function(index, value) {
                alert(index);           
            });
        });
    });
}; 
Run Code Online (Sandbox Code Playgroud)

似乎没有什么破坏,但最后一个警告存储中的内容的循环仍然显示我试图删除的所有值.

aps*_*ers 9

传入字符串时sync.remove,Chrome会尝试删除其键与输入字符串匹配的单个项目.如果需要删除多个项目,请使用一组键值.

此外,您应该将remove呼叫转移到get回调内部.

function clearNotes(symbol)
{
// CHANGE: array, not a string
var toRemove = [];

chrome.storage.sync.get( function(Items) {
    $.each(Items, function(index, value)
    {
        // CHANGE: add key to array
        toRemove.push(index);         
    });

    alert(toRemove);

    // CHANGE: now inside callback
    chrome.storage.sync.remove(toRemove, function(Items) {
        alert("removed");

        chrome.storage.sync.get( function(Items) {
            $.each(Items, function(index, value)
            {
                alert(index);           
            });
        });
    }); 
});

}; 
Run Code Online (Sandbox Code Playgroud)