允许用户在本地存储和同步存储之间进行选择的最佳实践?

问题描述

我正在尝试获取synclocal 存储之间切换的正确逻辑,以存储扩展设置以及在切换后如何认设置和处理。

  1. 首次安装扩展程序时,它应该使用同步存储还是本地存储?
  2. 用户打开/关闭扩展程序的同步设置时,当前设置应该应用于新存储(丢失该存储中的旧数据)还是切换到存储中的现有数据应该覆盖当前设置?

现在我正在使用这个逻辑: 启动扩展程序时,它会检查 storage.syncsyncSettings 设置。如果找到并且为真,则使用 storage.sync,否则使用 storage.local。如果用户决定通过将 syncSettings 更改为 true/false 来打开/关闭同步,它会分别切换到 storage.syncstorage.local 并将当前设置保存到选定的存储中,最终覆盖旧数据在那个存储中。

//set default settings
const settings = {
        blah: "ok",syncSettings: false
      };

var STORAGE = chrome.storage.sync;

//get all saves settings
STORAGE.get(null,initSettings);

function initSettings(items)
{
  if (items.syncSettings && STORAGE !== chrome.storage.sync)
  {
    STORAGE = chrome.storage.sync;
    STORAGE.set({syncSettings: true},res=>res&&console.log(res));
    return STORAGE.get(null,initSettings);
  }
  else if (!items.syncSettings && STORAGE !== chrome.storage.local)
  {
    STORAGE = chrome.storage.local;
    STORAGE.set({syncSettings: false},initSettings);
  }

  const del = [];

  //sanitize settings
  for(let i in items)
  {
    if (typeof items[i] == typeof settings[i])
      settings[i] = items[i];
    else
      del[del.length] = i;
  }

  if (del.length)
    STORAGE.remove(del); //remove non-existing/mismatched types settings

  console.log("initSettings",settings);
  return settings;
}

// storage change listener
chrome.storage.onChanged.addListener( (changes,area) =>
{
  for (let o in changes)
  {
    if (!("newValue" in changes[o]) || typeof changes[o].newValue != typeof settings[o])
      continue;

    settings[o] = changes[o].newValue;
  }

  if ("syncSettings" in changes)
  {
    STORAGE = chrome.storage[settings.syncSettings ? "sync" : "local"];
    STORAGE.set(settings);
  }
  console.log("settings changed",changes,settings);
});

您认为这是一种正确的逻辑/做法还是有更好的方法来处理切换存储?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)