chrome插件开发(三)- 数据存储的那些事儿

这篇文章发表于 阅读 1

chrome.storage提供了插件开发所需要的api

  • local: 存储在本地
  • sync: 会自动同步数据到用户的账号,如果用户下线就跟local一样保存在本地,上线后自动同步数据
  • session:存储数据到会话中,不会持久化道本地,浏览器关闭后消失。
  • managed: 只读存储,只有域管理员能够在其中存储数据,插件不能读取器中的数据
// set chrome.storage.local.set({name: "tom"}, () => { console.log('success') }); // get chrome.storage.local.get(["name"], (result) => { console.log(result["name"]) });

同时可以使用 chrome.storage.onChanged 监听数据的变化

//background.js chrome.storage.onChanged.addListener(function (changes, namespace) { for (let [key, { oldValue, newValue }] of Object.entries(changes)) { console.log( `Storage key "${key}" in namespace "${namespace}" changed.`, `Old value was "${oldValue}", new value is "${newValue}".` ); } });

持续更新中。。。