javascript 是否可以使用 HTML5 本地存储在来自不同站点的页面之间共享数据?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16144906/
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
Is it possible to use HTML5 local storage to share data between pages from different sites?
提问by Jér?me Verstrynge
I would like to create data on the user side and let javascript from another URL access it too. I am aware of the same origin policy, but I was wondering whether it is possible to create some exceptions. Or, is there any trick/feature I could use?
我想在用户端创建数据,并让来自另一个 URL 的 javascript 也访问它。我知道同源政策,但我想知道是否可以创建一些例外。或者,我可以使用任何技巧/功能吗?
回答by chrmod
Best trick I know is to use iframes and postMessage
API do get access to localStorage from external domain.
我知道的最好的技巧是使用 iframes 和postMessage
API 确实可以从外部域访问 localStorage。
This technique is quite simple:
这种技术非常简单:
- on you page you must create iframe to a domain from which you want to get data
your data domain need listen to
message
event:document.addEventListener ("message", handler, useCapture);
handler will be responsible for accessing
localStorage
and posting its content to source domain- your source domain may call
handler
function on data domain withpostMessage
API https://developer.mozilla.org/en-US/docs/DOM/window.postMessage
- 在您的页面上,您必须为要从中获取数据的域创建 iframe
您的数据域需要监听
message
事件:document.addEventListener ("message", handler, useCapture);
处理程序将负责访问
localStorage
其内容并将其发布到源域- 您的源域可以
handler
使用postMessage
API https://developer.mozilla.org/en-US/docs/DOM/window.postMessage在数据域上调用函数
For security of your data you can use HTTP header X-Frame-Options ALLOW-FROM urihttps://developer.mozilla.org/en-US/docs/HTTP/X-Frame-Options?redirectlocale=en-US&redirectslug=The_X-FRAME-OPTIONS_response_header
为了您的数据安全,您可以使用 HTTP 标头X-Frame-Options ALLOW-FROM uri https://developer.mozilla.org/en-US/docs/HTTP/X-Frame-Options?redirectlocale=en-US&redirectslug=The_X -FRAME-OPTIONS_response_header
Hope it will help.
希望它会有所帮助。