跨web应用程序和Chrome扩展共享本地存储对象



我需要在localStorage对象 cookies中存储用户配置文件和他的偏好,以使它们可以从web应用程序和chrome扩展(基本上是同一产品的一部分)访问(可读)和可写。

我发现了这个很酷的库,这篇文章详细说明了如何使用它。

问题是xauth.org关闭了,使用库所需的服务器页面也关闭了。

任何替代

可以同时使用localStorage和cookies

  1. 如果你在web应用程序的页面中注入一个内容脚本,它的localStorage与域自己的存储共享。

  2. 如果您在清单中包含"cookies"权限,您可以使用chrome.cookies API操作cookie

编辑:你也可以让你的扩展从外部连接到web应用程序,以保持同步的变化。

2016年更新

这个来自zendesk的交叉存储是你提到的两个库的一个很好的替代

更好的是,你可以配置哪些客户端站点/域具有特定的权限(获取,设置,删除)

示例代码:
Hub
// Config s.t. subdomains can get, but only the root domain can set and del
CrossStorageHub.init([
  {origin: /.example.com$/,            allow: ['get']},
  {origin: /://(www.)?example.com$/, allow: ['get', 'set', 'del']}
]);

注意$用于匹配字符串的末尾。上面示例中的regexp将匹配valid.example.com等来源,但不匹配invalid.example.com.malicious.com。

Client
var storage = new CrossStorageClient('https://store.example.com/hub.html');
storage.onConnect().then(function() {
  return storage.set('newKey', 'foobar');
}).then(function() {
  return storage.get('existingKey', 'newKey');
}).then(function(res) {
  console.log(res.length); // 2
}).catch(function(err) {
  // Handle error
});

最新更新