javascript 跨子域使用会话存储
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25064233/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using session-storage across subdomains
提问by binfull
I have two domains domain1.site.com and domain2.site.com, i have set session-storage in domain1.site.com and then not able to get session-storage on other domain domain2.site.com from same tab. Is there any other way which can be used identify a tab when navigated across sub-domains?
我有两个域 domain1.site.com 和 domain2.site.com,我在 domain1.site.com 中设置了会话存储,然后无法从同一个选项卡中获取其他域 domain2.site.com 上的会话存储。在跨子域导航时,还有其他方法可以用来识别选项卡吗?
回答by RiZKiT
The question is a bit older, but maybe the following helps others.
这个问题有点老了,但也许以下内容可以帮助其他人。
There is a solution called "Cross Domain Local Storage", it works with a combination of localStorage and postMessage. With that you have a storage you can use with any domain. There are two projects that I know:
有一种叫做“跨域本地存储”的解决方案,它结合了 localStorage 和 postMessage。有了它,您就有了一个可以用于任何域的存储。我知道有两个项目:
But that's not a session storage. To separate multiple tabs, you have to generate a unique id (maybe tab creation date in milliseconds) and save that into the session storage, but only the first time, when there is no value already in the session storage. That way you have one id per tab. That id you can use to put data into the cross domain local storage.
但这不是会话存储。要分隔多个选项卡,您必须生成一个唯一的 id(可能以毫秒为单位的选项卡创建日期)并将其保存到会话存储中,但仅限第一次,此时会话存储中已经没有值。这样你每个标签就有一个 id。您可以使用该 ID 将数据放入跨域本地存储中。
回答by Jeremy J Starcher
As @PaulS mentioned in his comment, you most likely mean to use localStorage
.
正如@PaulS 在他的评论中提到的,您很可能想使用localStorage
.
That said, you are still hindered by the Same Origin Policy.
也就是说,您仍然受到同源政策的阻碍。
If your example is correct, and both sites share the same top-level domain such as:
如果您的示例是正确的,并且两个站点共享相同的顶级域,例如:
domain1 .example.com
domain2 .example.com
域1 .example.com
域2 .example.com
Then you can set document.domain = "example.com";
to allow the two to share information.
然后可以设置document.domain = "example.com";
允许两者共享信息。
More detail on MDN: https://developer.mozilla.org/en-US/docs/Web/API/document.domain
有关 MDN 的更多详细信息:https: //developer.mozilla.org/en-US/docs/Web/API/document.domain