如何使用 Javascript 在本地存储中存储 cookie?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10747280/
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
How can I store a cookie in local storage with Javascript?
提问by Questioner
I have an app for Android (and hopefully later iPhone) that is based on Javacript and is made into an app using Phonegap/Applaud.
我有一个基于 Javacript 的 Android 应用程序(希望以后是 iPhone),并使用 Phonegap/Applaud 制作成一个应用程序。
Unfortunately, setting and getting cookies is not working on Android, and this might be particular to the Android environment. I was advised that using "local storage" might be more reliable.
不幸的是,设置和获取 cookie 在 Android 上不起作用,这可能是 Android 环境所特有的。有人建议我使用“本地存储”可能更可靠。
However, I knew nothing about local storage until this morning, and so I'm struggling to get aquainted. From what I gather, it's basically just another place to save data with a different syntax. For my situation, I don't think it gives me any advantages over cookies other than the fact that Android is forcing me to use it. As a result, I'm hoping I can still leverage my existing code for setting and getting cookies, and not have to take on a whole new approach.
然而,直到今天早上我才知道本地存储,所以我正在努力熟悉。从我收集的信息来看,它基本上只是另一个使用不同语法保存数据的地方。对于我的情况,除了 Android 强迫我使用 cookie 之外,我认为它没有给我任何优势。因此,我希望我仍然可以利用我现有的代码来设置和获取 cookie,而不必采用全新的方法。
Surely I can just do a test in my Javascript to see if there is local storage, and if so, store and retrieve my cookie data there, and if not, then just use cookies as normal?
当然,我可以在我的 Javascript 中做一个测试,看看是否有本地存储,如果有,在那里存储和检索我的 cookie 数据,如果没有,那么就照常使用 cookie?
Note 1:I searched Stack Overflow for similar questions, and there was this one which at first seems exactly what I'm talking about, but it's too terse so I can't parse it to know what I should do with it. Also, I think it assumes the presence of libraries and code that I don't think I have. I also looked at this questionbut I think it's doing the reverse of what I'm after.
注 1:我在 Stack Overflow 上搜索了类似的问题,有一个乍一看似乎正是我在谈论的问题,但它太简洁了,所以我无法解析它以知道我应该用它做什么。此外,我认为它假定存在我认为没有的库和代码。我也看过这个问题,但我认为它与我所追求的相反。
Note 2:This is my current code for getting and setting cookies (procured from somewhere on the web. Up until the Android problem, was rock solid reliable):
注 2:这是我当前用于获取和设置 cookie 的代码(从网络上的某个地方采购。直到 Android 问题,非常可靠):
function getCookie(c_name)
{
var c_start = document.cookie.indexOf(c_name + "=");
if (document.cookie.length > 0)
{
if (c_start !== -1)
{
return getCookieSubstring(c_start, c_name);
}
}
return "";
}
function setCookie(c_name, value, expiredays)
{
var exdate = new Date();
exdate.setDate(exdate.getDate() + expiredays);
document.cookie = c_name + "=" + escape(value) +
((expiredays === null) ? "" : ";expires=" + exdate.toUTCString());
alert("this is document.cookie: " + document.cookie);
}
回答by Bergi
Have a look at http://diveintohtml5.info/storage.html. The history might not be very interesting at all, but it at least provides an excellent link list to other tutorials in the further-reading section.
看看http://diveintohtml5.info/storage.html。这段历史可能根本不是很有趣,但它至少提供了一个很好的链接列表到进一步阅读部分中的其他教程。
So, now to your code. The first thing to mention is that localStorage
has no expire - it's persistent (until the user manually cleans everything). If you'd like to use some shorter storage, you might also use sessionStorage
, which has the same interface but last only until the browser is closed.
所以,现在到你的代码。首先要提到的是localStorage
没有过期 - 它是持久的(直到用户手动清理所有内容)。如果您想使用一些更短的存储空间,您也可以使用sessionStorage
,它具有相同的界面,但只持续到浏览器关闭。
Rephrasing your code is simple:
改写你的代码很简单:
function getCookie(c_name) {
return localStorage.getItem(c_name);
}
function setCookie(c_name, value, expiredays) {
return localStorage.setItem(c_name, value);
}
回答by Niet the Dark Absol
localStorage
behaves exactly like a regular Object.
localStorage
行为与普通对象完全一样。
localStorage.somekey = "My data"; // set
alert(localStorage.somekey); // get
delete localStorage.somekey; // unset
The only real difference between localStorage
and any other Object is that it is pesistent. Any page from the same origin can access the values in the object, and they even survive if the browser is closed.
localStorage
与任何其他对象之间唯一真正的区别是它是持久的。来自同一个源的任何页面都可以访问对象中的值,即使浏览器关闭,它们也能继续存在。
They are superior to cookies in every way for data storage, because they don't get sent to the server with every single request (although that's not to say cookies are useless - both have their advantages).
它们在数据存储的各个方面都优于 cookie,因为它们不会随着每个请求都发送到服务器(尽管这并不是说 cookie 没有用——两者都有其优点)。
It's really simple ;)
这真的很简单;)
回答by Questioner
I used the information in the other answers, so this isn't a different answer, but I just thought it would be helpful to others to see the complete code I ended up with. This can be pretty much dropped in as a replacement for using cookies (as I did). It tests for local storage, and uses that if present, and uses cookies if it isn't.
我使用了其他答案中的信息,所以这不是一个不同的答案,但我只是认为其他人看到我最终得到的完整代码会有所帮助。这几乎可以作为使用 cookie 的替代品(就像我所做的那样)。它测试本地存储,并在存在时使用它,如果不存在则使用 cookie。
Note you'll probably want to take out the alerts when implementing it.
请注意,您可能希望在实施时删除警报。
function getCookie(c_name)
{
if(typeof localStorage != "undefined")
{
return localStorage.getItem(c_name);
}
else
{
var c_start = document.cookie.indexOf(c_name + "=");
if (document.cookie.length > 0)
{
if (c_start !== -1)
{
return getCookieSubstring(c_start, c_name);
}
}
return "";
}
}
function setCookie(c_name, value, expiredays)
{
var exdate = new Date();
exdate.setDate(exdate.getDate() + expiredays);
if(typeof localStorage != "undefined")
{
alert("This place has local storage!");
localStorage.setItem(c_name, value);
}
else
{
alert("No local storage here");
document.cookie = c_name + "=" + escape(value) +
((expiredays === null) ? "" : ";expires=" + exdate.toUTCString());
}
}