javascript iframe 中的 sessionStorage

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32248128/
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-28 15:01:22  来源:igfitidea点击:

sessionStorage in iframe

javascriptiframesession-storage

提问by strannik

I'm going to have several iframes on my page and I'm going to quite intensively use sessionStorage inside them. What I'm curious about is if I will have separate storages or one shared for all iframes? How do the size limits apply?

我将在我的页面上有几个 iframe,并且我将在其中大量使用 sessionStorage。我很好奇的是我是否会有单独的存储或所有 iframe 共享一个?大小限制如何适用?

回答by Krassmus

If sessionStorage is shared depends on the iframe's page and it's origin, which is the domain part of the URL. If you have a webpage at http://myserver/test.htmland it is including http://thatserver/some.htmlvia an iframe, the iframe's page has the domain thatserver. Thus the origin differs and the sessionStorage won't be shared. But if the iframe's page is http://myserver/some.htmlit has the same origin and therefore will share the same session storage.

sessionStorage 是否共享取决于 iframe 的页面及其来源,即 URL 的域部分。如果您有一个网页 athttp://myserver/test.html并且它是http://thatserver/some.html通过 iframe包含的,则 iframe 的页面的域为thatserver。因此来源不同并且 sessionStorage 不会被共享。但是如果 iframe 的页面是http://myserver/some.html相同的,因此将共享相同的会话存储。

Now there is an additional trick: The sandboxattribute for the iframe. If you write <iframe sandbox>without the value allow-same-originthe content of the iframe gets a uniqueorigin. That means it would get a different sessionStorage regardless of the real origin that page has. You can write <iframe sandbox="allow-same-origin">to sandbox the content AND let the content of the iframe to have the same origin (but only if if does have the real same origin).

现在还有一个技巧:iframe的沙箱属性。如果您在<iframe sandbox>没有值allow-same-origin的情况下写入iframe 的内容将获得唯一的来源。这意味着无论页面的真实来源如何,它都会获得不同的 sessionStorage。您可以<iframe sandbox="allow-same-origin">将内容写入沙箱并让 iframe 的内容具有相同的来源(但前提是确实具有相同的来源)。

Now special notes: sandboxed iframes won't support localStorage per spec. And in webkit-browsers and mozilla firefox an exception will be thrown if the sandboxed iframe content will try to access sessionStorage.

现在特别注意:沙盒 iframe 将不支持每个规范的localStorage 。在 webkit 浏览器和 mozilla firefox 中,如果沙盒 iframe 内容尝试访问 sessionStorage,则会抛出异常。

回答by strannik

OK, I've made a test myself. At least in Chrome (44) and Firefox (40) the sessionStorage is shared among page and the iframes included if they are of the same domain and do not if they are of different domains.

好的,我自己做了一个测试。至少在 Chrome (44) 和 Firefox (40) 中, sessionStorage 在页面和包含的 iframe 之间共享,如果它们属于同一域,则不会在它们属于不同域的情况下共享。