2016-07-08 32 views

cevap

8

İlk kapatma, chrome.storage zaman uyumsuz olduğundan, her şey geri aramada yapılmalıdır - dışarıda hiçbir şey döndürmeyeceğiniz için (henüz), if...else dışarıda olamazsınız. Chrome, sorguna her ne olursa olsun, geri dönüş anahtar kelimesi olarak (yalnızca bir anahtar için sorulmuş olsa bile) geri bildirime geçer.

Yani,

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 

değeri undefined ve depolama olmama arasında hiçbir ayrım yoktur. Yani bunun için test edebilirsiniz:

söyledi
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 
    } 
}); 

, chrome.storage bu işlem için daha iyi bir modeli vardır. Sen get() için varsayılan bir değer sağlayabilir:

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

başlangıçta olurdu olarak ayarlayabilmek için iyi bir yer; Bir arka plan/etkinlik sayfasındaki chrome.runtime.onStartup ve/veya chrome.runtime.onInstalled olayları en uygunudur.

İlgili konular