可以跨子域共享HTML5数据库和localStorage吗?

Seb*_*lis 60 database subdomain dns html5 local-storage

我正在尝试使用Safari在子域之间共享数据.我想使用HTML5数据库(特别是localStorage,因为我的数据只是键值对).但是,似乎无法从sub.domain.com访问存储到domain.com的数据(反之亦然).在这种情况下有没有办法共享一个数据库?

sup*_*ha1 12

2016年更新

Zendesk的这个图书馆为我工作.

样品:

// 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']}
]);
Run Code Online (Sandbox Code Playgroud)

请注意$匹配字符串的结尾.上例中的正则表达式将匹配起源,例如valid.example.com但不是invalid.example.com.malicious.com.

客户

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
});
Run Code Online (Sandbox Code Playgroud)

检查/sf/answers/2785211971/


jcu*_*bic 10

有一种简单的方法可以使用跨域的任何东西,只需创建一个简单的页面,它将作为托管在您尝试访问的域上的代理iframe包含在内,将PostMessage发送到该iframe,并在iframe内部进行LocalStorage数据库操作.以下是使用lcoalStorage执行此操作的文章的链接.以下是在子域中向不同页面发送消息的演示检查源代码,它使用iframe和PostMessage.

  • 它只是我还是那种有臭味的解决方案?听起来像kludgey.(没有downvote ......只是说). (11认同)

Mad*_*ist 5

默认情况下,谷歌浏览器会阻止来自另一个域中 iFrame 的 localStoage 访问,除非启用了 3rd 方 cookie,iPhone 上的 Safari 也是如此……唯一的解决方案似乎是在不同域上打开父域,然后发送给子域通过 window.postMessage 但在手机上看起来又丑又狡猾...