700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > chrome拓展插件开发中使用chrome.storage本地存储

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

时间:2019-02-27 09:41:09

相关推荐

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

一、描述

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

与 localStorage 的区别:

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

二、权限申请

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

三、local 与 sync 的使用不同

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

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

storage.managed 是只读的

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

1、chrome.storage.sync

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

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

结果展示:

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

2、clear

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

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。