【问题标题】:Browser cookie storage浏览器 cookie 存储
【发布时间】:2021-10-13 13:08:58
【问题描述】:

我正在制作一个浏览器游戏,它被导入以保存数据以保持您的进度。这是我用来保存每个变量的代码:

function autosave() {
  localStorage.setItem("variablename", variablename);
}
setInterval(autosave, 1000);

但是,我注意到 Chrome 等浏览器每个域只能存储 50 个 cookie。每个变量都算作一个 cookie 吗?如果是这样,我该如何解决这个问题。

【问题讨论】:

标签: javascript cookies save load autosave


【解决方案1】:

你说的是“饼干”对吧?这是来自tutorialsrepublic.com的方法



设置 Cookies

function setCookie(name, value, daysToLive) {
    // Encode value in order to escape semicolons, commas, and whitespace
    var cookie = name + "=" + encodeURIComponent(value);
    
    if(typeof daysToLive === "number") {
        /* Sets the max-age attribute so that the cookie expires
        after the specified number of days */
        cookie += "; max-age=" + (daysToLive*24*60*60);
        
        document.cookie = cookie;
    }
}

获取 Cookies

function getCookie(name) {
    // Split cookie string and get all individual name=value pairs in an array
    var cookieArr = document.cookie.split(";");
    
    // Loop through the array elements
    for(var i = 0; i < cookieArr.length; i++) {
        var cookiePair = cookieArr[i].split("=");
        
        /* Removing whitespace at the beginning of the cookie name
        and compare it with the given string */
        if(name == cookiePair[0].trim()) {
            // Decode the cookie value and return
            return decodeURIComponent(cookiePair[1]);
        }
    }
    
    // Return null if not found
    return null;
}

要重新分配 cookie,只需使用与设置相同的 cookie。

setCookie(Name, NewValue, Days)

示例:
最后,您可以使用删除cookies

setCookie(Name, '', 0)

对于本地存储,Go here

【讨论】:

  • 谢谢,但我注意到我不是在谈论 cookie,而是在谈论本地存储。
  • 我该怎么做,对不起,我是新人
  • 检查底部;我添加了指向 MDN 的链接
【解决方案2】:

localStorage 和 cookie 不同。

如果您对 localStorage 的限制感到好奇,请查看this question。

【讨论】:

    猜你喜欢
    • 2018-10-30
    • 2017-10-07
    • 2021-06-29
    • 2021-06-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-05
    • 1970-01-01
    相关资源
    最近更新 更多