2

我在做一個小的Chrome擴展。我想使用chrome.storage,但我無法從存儲中刪除多個項目(數組)。單件清除工程。chrome.storage.sync.remove數組不工作

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);   
      }); 
     }); 
    }); 
}; 

似乎沒有什麼突破,但可以提醒什麼是存儲最後的循環仍然顯示了所有我想刪除的值。

+0

就是這樣!謝謝。將其作爲答案提交,以便將其標記爲解決方案。 – americanslon

回答

5

當您將字符串傳遞到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);   
      }); 
     }); 
    }); 
}); 

};