标准的 W3C 标准是关于 localStorages 的:
Different authors sharing one host name, for example users hosting content on
geocities.com
, all share one local storage object. There is no feature to restrict the access by pathname. Authors on shared hosts are therefore urged to avoid using these features, as it would be trivial for other authors to read the data and overwrite it.
但是对于 sessionStorages,据说它确实为标签页和窗口提供了单独的 sessionStorages,即使来自同一来源也是如此。
但似乎 iframe 确实共享 sessionStorage。
有没有一种方法可以通过同一来源的 iframe 建立单独的 sessionStorages。
编辑: 由于如果选项卡/窗口确实有单独的 sessionStorages 会造成混淆,这里是一个示例页面。将代码保存在一个文件中,然后使用两个不同的选项卡将其打开。然后刷新一个选项卡 5 次,刷新另一个选项卡 1 次。您会看到数字不同。
<!DOCTYPE html>
<html>
<body>
<div id="result"></div>
<script>
sessionStorage.setItem("counter", (parseInt(sessionStorage.getItem("counter"), 10) || 0 ) + 1);
document.getElementById("result").innerHTML = sessionStorage.getItem("counter");
</script>
</body>
</html>
Edit2:到目前为止我尝试过的是使用 iframe sandbox
属性。但是后来我在 iframe 中遇到错误,我根本无法使用 sessionStorage。我必须添加 sandbox="allow-same-origin"
。但随后所有 iframe 中的 sessionStorage 再次相同。
提前致谢。
最佳答案
如果您有 ssl,则有一个解决方法。使用 https://... 访问一个文档并使用 http://... 访问另一个文档将为同一来源创建单独的存储。
关于javascript - 如何为同一来源的 iframe 设置单独的 sessionStorages,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35065157/