如何检查chrome.storage中是否设置了密钥?

shu*_*014 11 javascript google-chrome-extension

我正在制作Google Chrome扩展程序,我想检查是否设置了密钥chrome.storage.sync.

示例:
我想检查密钥'links':

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

任何有用的建议将不胜感激.

Xan*_*Xan 20

首先,因为chrome.storage是异步的,所有事情都必须在回调中完成 - 你不能if...else在外面,因为什么都不会被返回(还).无论Chrome如何回答查询,它都会将回调作为键值字典传递给回调(即使您只需要一个键).

所以,

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
Run Code Online (Sandbox Code Playgroud)

价值undefined与不存储之间没有区别.所以你可以测试一下:

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 
  }
});
Run Code Online (Sandbox Code Playgroud)

也就是说,chrome.storage这个操作有更好的模式.您可以提供以下默认值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
  });
});
Run Code Online (Sandbox Code Playgroud)

设置默认值的好地方是启动时; chrome.runtime.onStartup和/或chrome.runtime.onInstalled背景/事件页面中的事件最适合.