javascript 为什么两个网页有不同的localStorage?我怎样才能解决这个问题?

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

Why do two web pages have different localStorage? How can I fix this?

javascripthtmllocal-storage

提问by theUtherSide

I'm trying to pass a value from one page to another using localStorage. Both pages use a common JS file to get/set values from localStorage. This page sets the value appropriately using localStorage.setItem('key', 'value'): http://example.com/path/index.html

我正在尝试使用 localStorage 将值从一个页面传递到另一个页面。两个页面都使用一个共同的 JS 文件从 localStorage 获取/设置值。此页面使用localStorage.setItem('key', 'value')以下方法适当设置值:http: //example.com/path/index.html

ipis parsed from the query string and written to localStorage with key db_ip.

ip从查询字符串中解析出来并使用 key 写入 localStorage db_ip

When I try to do localStorage.getItem('db_ip')on this page, then the item is not there: http://www.example.com/path/page.html

当我尝试localStorage.getItem('db_ip')在此页面上执行操作时,该项目不存在:http: //www.example.com/path/page.html

I'm reading specs that say "every Document object whose Window object's localStorage attribute's Storage object is associated with the same storage area", so this makes me think pages can have separate localStorage by having a different Storage object.

我正在阅读的规范说“每个 Document 对象的 Window 对象的 localStorage 属性的 Storage 对象都与相同的存储区域相关联”,所以这让我认为页面可以通过具有不同的 Storage 对象来拥有单独的 localStorage 。

I can see the Storage object is different between the two pages. How to I make both pages use the same Storage object?

我可以看到两个页面之间的 Storage 对象不同。如何让两个页面使用相同的 Storage 对象?

回答by plalx

The localStorageisin't per page, it's by domain. However like @bfavaretto mentionned, www.demandbaselabs.comand demandbaselabs.comaren't considered as the same domain.

localStorage每页isin't,它是由域。然而,就像@bfavaretto 提到的那样,www.demandbaselabs.comdemandbaselabs.com不被视为同一个域。

Have a look at this answerto see how you can exchange client-side stored data between domains.

查看此答案,了解如何在域之间交换客户端存储的数据。