JavaScript 如何设置一个永不过期的cookie

JavaScript 如何设置一个永不过期的cookie

我们可以通过以下方法在JavaScript中设置一个永不过期的cookie:

先决条件:

  • 具备中级级别的JavaScript知识
  • 基本的HTML

    免责声明: 根据cookie规范,所有的cookie都有过期时间。因此,在JavaScript中无法编写代码设置一个永不过期的cookie。这是不可能的事实。

    解决方案: 但是,你可以在JavaScript中设置一个过期时间极大的cookie,如下所示:

document.cookie = "cookieName= true; expires=Fri, 31 Dec 9999 23:59:59 GMT";

注意: 但是浏览器在2038年01月19日04:14:07之后的日期存在问题,因为Unix纪元时间超过了32位整数。这个问题也被称为 2038年问题(也称为Y2038,Epochalypse,Y2k38或Unix Y2K)。

因此,您可以设置的cookie到期日期的最大值是由大多数Web浏览器支持的:

2^31 - 1 = 2147483647 ie. 2038-01-19 04:14:07 

语法:

document.cookie = "cookieName= true; expires=Tue, 19 Jan 2038 04:14:07 GMT";

// OR
const cookieName = "something";
const cookieValue = "something";
const daysToExpire = new Date(2147483647 * 1000).toUTCString();
document.cookie = cookieName + '=' + cookieValue + '; expires=' + daysToExpire;

代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script type="text/javascript">
        const createCookieWithY2K38 = (cookieName, cookieValue) => {
 
            // Expiry date conversion into UTC standard string
            const daysToExpire = new Date(2147483647 * 1000).toUTCString();
 
            // Setting up the cookie name, value with the expiry date 
            document.cookie =
                cookieName + '=' + cookieValue + '; expires=' + daysToExpire;
            alert('Welcome ' + cookieValue);
        }
        const extractUserNameFromCookie = (cookieName) => {
            var userName = cookieName + '=';
 
            // Splitting cookie
            var allCookieArray = document.cookie.split(';');
            for (var i = 0; i < allCookieArray.length; i++) {
 
                // Extracting userName and returning the same
                var temp = allCookieArray[i].trim();
                if (temp.indexOf(userName) == 0)
                    return temp.substring(userName.length, temp.length);
            }
 
            // Else return empty string 
            return '';
        }
        const readCookieAndGreetUser = () => {
            var userName = extractUserNameFromCookie('testCookie');
            if (userName != '') {
                //  If user is visiting the page again 
                // "user" variable will not be a empty string
                // returned by the accessCookie() function
                // and will greet the user
                alert('Welcome ' + userName);
            }
            else {
                userName = prompt('Please enter your name');
                if (userName != '' && userName != null) {
                    createCookieWithY2K38('testCookie', userName);
                }
            }
        }
    </script>
</head>
<body onload="readCookieAndGreetUser()"></body>
</html>

输出:

JavaScript 如何设置一个永不过期的cookie

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程