Javascript 检查 cookie 是否存在,否则将 cookie 设置为 10 天后过期

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

Check if cookie exists else set cookie to Expire in 10 days

javascriptcookies

提问by Learning

Here is what I'm looking to do (pseudo-code):

这是我想要做的(伪代码):

Imagine the name of the cookie in the example is "visited" and it contains nothing.

想象一下,示例中 cookie 的名称是“已访问”并且它不包含任何内容。

if visited exists
then alert("hello again");
else
create visited - should expire in 10 days;
alert("This is your first time!")

How can I achieve this in JavaScript?

我如何在 JavaScript 中实现这一点?

回答by Michael Berkowski

You need to read and write document.cookie

你需要阅读和写作 document.cookie

if (document.cookie.indexOf("visited=") >= 0) {
  // They've been here before.
  alert("hello again");
}
else {
  // set a new cookie
  expiry = new Date();
  expiry.setTime(expiry.getTime()+(10*60*1000)); // Ten minutes

  // Date()'s toGMTSting() method will format the date correctly for a cookie
  document.cookie = "visited=yes; expires=" + expiry.toGMTString();
  alert("this is your first time");
}

回答by Ry-

if (/(^|;)\s*visited=/.test(document.cookie)) {
    alert("Hello again!");
} else {
    document.cookie = "visited=true; max-age=" + 60 * 60 * 24 * 10; // 60 seconds to a minute, 60 minutes to an hour, 24 hours to a day, and 10 days.
    alert("This is your first time!");
}

is one way to do it. Note that document.cookieis a magic property, so you don't have to worry about overwriting anything, either.

是一种方法。请注意,这document.cookie是一个神奇的属性,因此您也不必担心覆盖任何内容。

There are also more convenient libraries to work with cookies, and if you don't need the information you're storing sent to the server on every request, HTML5's localStorageand friendsare convenient and useful.

还有更方便的库来处理 cookie,如果您不需要在每次请求时将存储的信息发送到服务器,HTML5localStorage和朋友们都非常方便和有用。