一、描述

在扩展程序中本地存储数据可以通过 chrome.storage API 实现,和 web 中的 localstorage 在某些方面是有区别的,chrome.storage 已经做了优化。

与 localStorage 的区别:

  • 用户数据可以与 chrome 自动同步(通过 storage.sync),只要用户登录了 chrome 账号,则能够全量同步浏览器
  • 扩展程序的脚本能够直接访问用户的数据,不需要通过 background js
  • 即使使用 split 隐身行为,也可以保留用户的扩展程序设置
  • 异步批量读写操作,比阻塞和串行的 localStorage 更快
  • 用户数据可以存储对象(localStorage 是将对象 string 到字符串中)
  • 可以读取管理员为扩展配置的企业策略(使用带有模式的 storage.managed 做 schema)

二、权限申请

如果要使用 chrome.storage 则需要在 manifest 的 permissions 申请:

chrome拓展插件开发中使用chrome.storage本地存储

三、local 与 sync 的使用不同

使用 storage.sync 时,如果用户启用了同步,则存储的数据将自动同步到用户登录的任何 Chrome 浏览器。

当 Chrome 处于离线状态时,Chrome 会在本地存储数据。下次浏览器在线时,Chrome 会同步数据。即使用户禁用同步,storage.sync 仍然可以工作。在这种情况下,它的行为与 storage.local 相同。

storage.managed 是只读的

存储是未加密的,不能存储机密信息

1、chrome.storage.sync

如果需要将存储的内容同步到所有登录了同一账号的 chrome 浏览器中,可以通过 chrome.storage.sync

// popup.js
button.onclick = () => {
    chrome.storage.sync.set({key: 'value11'}, () => {
        console.log('set successed!');
    });
}
button2.onclick = () => {
    chrome.storage.sync.get('key', (res) => {
        console.log(res);
    });
}

 结果展示:

 chrome拓展插件开发中使用chrome.storage本地存储

chrome拓展插件开发中使用chrome.storage本地存储 

2、chrome.storage.local

button3.onclick = () => {
    chrome.storage.local.set({key: "value local"}, function() {
        console.log('Value is set to ' + value);
    });
    chrome.storage.local.get(['key'], function(result) {
        console.log('Value currently is ' + result.key);
    });
}

结果展示:

chrome拓展插件开发中使用chrome.storage本地存储

四、存储限制

chrome.storage 的存储是有限制的,类似一个管道。

当管道满了之后,就会排队,因此可能无法继续存储。

五、使用示例及存储对象变更监听

存储内容变更之后,是能够监听到事件的,比如我做了下面的存储。

    const text = textarea.value;
    chrome.storage.local.set({'textValue': text}, function() {
        console.log('Value is ' + text);
    });

可以通过如下监听:

chrome.storage.onChanged.addListener(function(changes, namespace) {
        for (var key in changes) {
          var storageChange = changes[key];
          console.log('Storage key "%s" in namespace "%s" changed. ' +
                      'Old value was "%s", new value is "%s".',
                      key,
                      namespace,
                      storageChange.oldValue,
                      storageChange.newValue);
        }
      });

六、API 示例

set 和 get 上面已经有了,不重复

remove 和 get 两个方法均支持 单个参数或者是数组形式的参数

1、remove

button6.onclick = () => {
    chrome.storage.local.remove('textValue', function() {
        console.log('remove ');
    });
}

chrome拓展插件开发中使用chrome.storage本地存储

2、clear

button7.onclick = () => {
    chrome.storage.local.clear(function() {
        console.log('remove all ');
    });
}

chrome拓展插件开发中使用chrome.storage本地存储

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。