浏览器 cookie 存储
Browser cookie storage
我正在制作一个浏览器游戏,它被导入以保存数据以保持您的进度。这是我用来保存每个变量的代码:
function autosave() {
localStorage.setItem("variablename", variablename);
}
setInterval(autosave, 1000);
但是,我注意到 chrome 等浏览器每个域只能存储 50 个 cookie。每个变量算作一个 cookie 吗?如果是这样,我该如何解决这个问题。
localStorage 和 cookies 不同
如果您对 localStorage 的限制感到好奇,请查看 this question。
你说'Cookies'对吧?这是来自 tutorialsrepublic.com
的方法
设置 Cookies
function setCookie(name, value, daysToLive = undefined) {
// 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)
示例:
最后,要删除 cookie,您可以使用
setCookie(Name, '', 0)
对于本地存储,Go here
我正在制作一个浏览器游戏,它被导入以保存数据以保持您的进度。这是我用来保存每个变量的代码:
function autosave() {
localStorage.setItem("variablename", variablename);
}
setInterval(autosave, 1000);
但是,我注意到 chrome 等浏览器每个域只能存储 50 个 cookie。每个变量算作一个 cookie 吗?如果是这样,我该如何解决这个问题。
localStorage 和 cookies 不同
如果您对 localStorage 的限制感到好奇,请查看 this question。
你说'Cookies'对吧?这是来自 tutorialsrepublic.com
的方法
设置 Cookies
function setCookie(name, value, daysToLive = undefined) {
// 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)
示例:
最后,要删除 cookie,您可以使用
setCookie(Name, '', 0)
对于本地存储,Go here