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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 03:26:07  来源:igfitidea点击:

Is it possible to use HTML5 local storage to share data between pages from different sites?

javascripthtmllocal-storagesame-origin-policy

提问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 postMessageAPI do get access to localStorage from external domain.

我知道的最好的技巧是使用 iframes 和postMessageAPI 确实可以从外部域访问 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 messageevent:

    document.addEventListener ("message", handler, useCapture);

  • handler will be responsible for accessing localStorageand posting its content to source domain

  • your source domain may call handlerfunction on data domain with postMessageAPI https://developer.mozilla.org/en-US/docs/DOM/window.postMessage
  • 在您的页面上,您必须为要从中获取数据的域创建 iframe
  • 您的数据域需要监听message事件:

    document.addEventListener ("message", handler, useCapture);

  • 处理程序将负责访问localStorage其内容并将其发布到源域

  • 您的源域可以handler使用postMessageAPI 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.

希望它会有所帮助。