2016-07-08 31 views
7

Sto creando un'estensione Google Chrome e voglio verificare se una chiave è impostata o meno in chrome.storage.sync.Come verificare se una chiave è impostata in chrome.storage?

Esempio:
voglio controllare la chiave 'links':

if (chrome.storage.sync.get('links',function(){ 
    // if already set it then nothing to do 
})); 
else{ 
    // if not set then set it 
} 

Ogni suggerimento utile sarà apprezzato.

risposta

8

Prima di tutto, poiché chrome.storage è asincrono, tutto deve essere eseguito nella richiamata - non è possibile if...else all'esterno, perché non verrà restituito nulla (ancora). Qualsiasi cosa Chrome risolva la query passa al callback come dizionario dei valori-chiave (anche se hai chiesto solo una chiave).

Quindi,

chrome.storage.sync.get('links', function(data) { 
    if (/* condition */) { 
    // if already set it then nothing to do 
    } else { 
    // if not set then set it 
    } 
    // You will know here which branch was taken 
}); 
// You will not know here which branch will be taken - it did not happen yet 

non c'è distinzione tra il valore undefined e di non essere in deposito. Così si può verificare che:

chrome.storage.sync.get('links', function(data) { 
    if (typeof data.links === 'undefined') { 
    // if already set it then nothing to do 
    } else { 
    // if not set then set it 
    } 
}); 

Detto questo, chrome.storage ha un modello migliore per questa operazione. È possibile fornire un valore predefinito per get():

var defaultValue = "In case it's not set yet"; 
chrome.storage.sync.get({links: defaultValue}, function(data) { 
    // data.links will be either the stored value, or defaultValue if nothing is set 
    chrome.storage.sync.set({links: data.links}, function() { 
    // The value is now stored, so you don't have to do this again 
    }); 
}); 

Un buon posto per impostare i valori predefiniti sarebbe in fase di avvio; Gli eventi chrome.runtime.onStartup e/o chrome.runtime.onInstalled in una pagina di sfondo/evento si adattano meglio.