I am making a browser game where it is import to save data to keep your progress. This is the code I am using to save each variable:
function autosave() {
localStorage.setItem("variablename", variablename);
}
setInterval(autosave, 1000);
However, it has come to my attention that browsers such as chrome can only store 50 cookies per domain. Does each variable count as one cookie? If so, how can I work around this.
localStorage and cookies are different.
If you're curious about the limits of localStorage check out this question.
You said 'Cookies' Right? Here is a method from tutorialsrepublic.com
To set 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;
}
To get 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;
}
And to reassign cookies, just use the same one as set.
setCookie(Name, NewValue, Days)
Example:
Finally, to delete cookies you can use
setCookie(Name, '', 0)
For Localstorage, Go here
Related
I have looked at many SO and haven't been able to figure out how to actually make this work using pure JS. My problem is that I need to add a 2 different urls to a json array and store it into a cookie for access across subdomains (i looked into the iframe local storage thing and it won't work for this application and the json array will be rather small so 4k cookie limit is plenty).
Now what I have is the following:
function getProject(){
var url_str = window.location.href;
var ProjectImgId = url_str.split('projectId=')[1];
ProjectImgId = ProjectImgId.split('&')[0];
var UserId = url_str.split('flashId=')[1];
var ImageURL = 'https://project-api.artifactuprising.com/project/' + ProjectImgId + '/thumbnail?user=' + UserId;
var RecentProjects = {"url" : url_str, "img" : ImageURL};
return RecentProjects;
}
The above will run on a certain page load. I want to be able to do the following with this: retrieve any existing Projects and if there isn't a match on the url, I wan to push the RecentProjects to the cookie array.
Here is where I am getting stumped. I am following w3 School's cookie set up which has worked for me in the past but I am unable to figure out how to push and pull this data using stringify and parse.
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
var expires = "expires="+d.toUTCString();
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
function checkCookie() {
var recent = getCookie("yourRecentProjects");
if (recent != "") {
// this is where I would want to parse the JSON and then check if the getProject.url value is in the current cookie json and if it is not, push it.
} else {
recent = getProject();
if (recent != "" && recent != null) {
setCookie("yourRecentProjects", recent, 365);
}
}
}
I am pretty stumped. I have figured out how to do all this using local storage, then i realized this doesn't work across subdomains so great learning experience but not a solution. Any help would be appreciated.
well, the cookie isn't json, it's just a string with a bunch of key values.
not 100% what you are looking to do with the data, but as an example, this is taken from the MDN, example #3, as for how to parse that string to find a specific value: https://developer.mozilla.org/en-US/docs/Web/API/Document/cookie:
function doOnce() {
if (!document.cookie.split('; ').find(row => row.startsWith('doSomethingOnlyOnce'))) {
alert("Do something here!");
document.cookie = "doSomethingOnlyOnce=true; expires=Fri, 31 Dec 9999 23:59:59 GMT";
} }
String.prototype.split() creates an array of substring segments that are delimited by the value you pass in, the Array.prototype.find() will look at each value in the array until it either finds the substring that starts with that value, or returns undefined if it finds nothing.
In you case, you'd do document.cookie.split("") to create the array of key value substrings, which at that point you can unpack the data in many ways. maybe you are just looking for the existence of the url value, in which case Array.prototype.includes() is what you are looking for.
I am new to JavaScript and cookies, so I have this weird question as different websites had different format. So I had confusion on how the cookies read and access the different parts of it, i.e. how do cookies recognize names from path or expiration date? Do we always have to specify "username=...;path=/;" for it to recognize it or does it automatically find it based on the format?
And the main question that I am trying to figure is how I can add a value to the cookie creation code, such as a " document.cookie="username=John;visit=1;" and use that visit part to tell the hit count by adding 1 to it every time the page loads.
Thank you!
I use two functions (maybe the original code was from here or here) for getting and setting cookies, here are they:
function setCookie(cookieName, content, expires, path) {
var date = new Date();
date.setDate(date.getDate() + expires);
var cookie = escape(content) + (expires == null ? "" : "; expires=" + date.toUTCString()) + (path != null ? "; path=" + path : "");
document.cookie = cookieName + "=" + cookie;
return true;
}
function getCookie(cookieName) {
var cookie = document.cookie,
begin = cookie.indexOf(" " + cookieName + "=");
if (begin == -1) begin = cookie.indexOf(cookieName + "=");
if (begin == -1) cookie = null;
else {
begin = cookie.indexOf("=", begin) + 1;
var end = cookie.indexOf(";", begin);
if (end == -1) end = cookie.length;
cookie = unescape(cookie.substring(begin, end));
}
return cookie;
}
With them you can easily do what you want:
Handle the page loads (eg <body onload="pageLoad()">)
Add a script element to the head part of the page, and the two funtions above
Add the following function inside the script element:
function pageLoad() {
var cCont = getCookie('hitCount');
var count = 0;
if (cCont != null) count = parseInt(count + '');
setCookie('hitCount', (count + 1) + '', null, null);
}
If you want to get the hit count, you can use the count variable, or use the getCookie function again.
Your first question is not totally clear to me, but read this page, there are nice examples and code samples. This is another good presentation of cookies.
I am using Javascript to set the cookie and read the value from cookie.I am using the code available at http://www.w3schools.com/js/js_cookies.asp for creating and reading the value of cookie.when the page loads i am checking that whether that cookie exists or not .Every thing is working fine except it is not reading the cookie when i set it first time and try to read in next page load .it is setting the cookie but does not read only first time .
Here is my code :-
function setCookie(c_name, value, exdays) {
var exdate = new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value = escape(value) + ((exdays == null) ? "" : "; expires=" + exdate.toUTCString());
document.cookie = c_name + "=" + c_value;
}
//To get the cookie:-
function getCookie(c_name) {
var i, x, y, ARRcookies = document.cookie.split(";");
for (i = 0; i < ARRcookies.length; i++) {
x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("="));
y = ARRcookies[i].substr(ARRcookies[i].indexOf("=") + 1);
x = x.replace(/^\s+|\s+$/g, "");
if (x == c_name) {
return unescape(y);
}
}
}
//to Delete the cookie:-
function cookieDelete(c_name) {
setCookie(c_name, "delete", -1);
}
And on page load i am using it like :-
$(document).ready(function () {
var aZ = getCookie("menuSave");
if (aZ) {
//do Some thing here
}
else {
setCookie("menuSave", "mysp", null);
}
});
You need to add a 'path' to your cookie. For example:
document.cookie = 'ppkcookie2=yet another test; expires=Fri, 27 Jul 2001 02:47:11 UTC; path=/';
The path represents the relative path in your website which the cookie will be readable.
path=/ means it'll be readable on your whole website.
path=/common/ means it'll be readable only in /common/ folder (and its subfolders)
This might not be the answer to your problem but yet a alternative easier solution, hope it helps!
save menu
localStorage.setItem("menusave","vale");
load value
localStorage.getItem("menusave");
Just trying to help!
Since you have marked the question as asp.net,
You can set the cookies as follows:
HttpCookie aCookie = new HttpCookie("lastVisit");
aCookie.Value = DateTime.Now.ToString();
aCookie.Expires = DateTime.Now.AddDays(1);
Response.Cookies.Add(aCookie);
And read it back like:
if(Request.Cookies["lastVisit"] != null)
Label1.Text = Server.HtmlEncode(Request.Cookies["lastVisit"].Value);
Refer MSDN Cookies overview
When you pass null for the expiration days it makes your cookie into a session cookie that will not persist very long.
Change this:
setCookie("menuSave", "mysp", null);
to this to give it an actual expiration date:
setCookie("menuSave", "mysp", 7);
If you want to retrieve the cookie from any page besides the exact same page that set it, you will also need to set a path value in the cookie that allows the cookie to be retrieved on more than just the exact page that set it.
This is the script that i am using to fetch a particular cookie lastvisit :
AFTER THE EDIT
// This document writes a cookie
// called from index.php
window.onload = makeLastVisitCookie;
function makeLastVisitCookie() {
var now = new Date();
var last = new Date();
now.setFullYear(2020);
// set the cookie
document.cookie = "lastvisit=" + last.toDateString() + ";path=/;expires=" + now.toGMTString();
var allCookies = document.cookie.split(";");
for( var i=0 ; i < allCookies.length ; i++ ) {
if(allCookies[i].split("=")[0]== "lastvisit") {
document.getElementById("last_visit").innerHTML = "You visited this site on" + allCookies[i].split("=")[1];
} else {
alert("testing..testing..");
}
}
}
From this script the if part never works though there are 5 cookies stored from my website. (including the cookie that i am saving from this script) What is the mistake that i am making while fetching the cookie named lastvisit ?
You're splitting the cookie by ; an comparing those tokens with lastvisit. You need to split such a token by = first. allCookies[i] looks like key=val and will never equal lastvisit. Een if allCookies[i] == "lastvisit" is true, the result will still not be as expected since you're showing the value of allCookies[i + 1] which would be this=the_cookie_after_lastvisit.
if(allCookies[i].split("=") == "lastvisit") { should be:
var pair = allCookies[i].split("=", 2);
if (pair[0].replace(/^ +/, "") == "lastvisit") {
"You visited this site on" + allCookies[i+1]; should be:
"You visited this site on" + pair[1];
The 2 argument of split makes cookies like sum=1+1=2 be read correctly. When splitting cookies by ;, the key may contain a leading space which much be removed before comparing. (/^ +/ is a regular expression where ^ matches the beginning of a string and + one or more spaces.)
Alternatively, compare it directly against a RE for matching the optional spaces as well (* matches zero or more occurences of a space character, $ matches the end of a string):
if (/^ *lastvisit$/.test(pair[0])) {
I've tested several ways to get a cookie including using regular expressions and the below was the most correct one with best performance:
function getCookie(name) {
var cookie = "; " + document.cookie + ";";
var search = "; " + encodeURIComponent(name) + "=";
var value_start = cookie.indexOf(search);
if (value_start == -1) return "";
value_start += search.length;
var value_end = cookie.indexOf(';', value_start);
return decodeURIComponent(cookie.substring(value_start, value_end))
}
You need to remove possible white space around the cookie key before comparing to the string "lastvisit". This is done conveniently using regular expressions. /^\s+/ matches all white space at the beginning, /\s+$/ matches all white space at the end. The matches are replaced by the empty string, i.e. removed:
for( var i = 0 ; i < allCookies.length ; i++ ) {
var c = allCookies[i].split("="); // split only once
var key = c[0].replace(/^\s+/, '').replace (/\s+$/, ''); // remove blanks around key
if (key == "lastvisit") {
document.getElementById("last_visit").innerHTML = "You visited on " + c[1];
}
//...
}
I am having trouble grasping what the 'value' field of a cookie needs to be. Does the 'value' field need to reference a variable found somewhere with the following javascript code, or is it something completely random?
The reason I ask, is b/c I am trying to put cookies on a project I am working on, but obviously I can't get them to work... here is what I have so far, but my main question is an elaborate definition of the value (physics) field and possibly an example that references some Jscript.
function createCookie(child,physics,d82){
if (d82) {
var date = new Date();
date.setTime(date.getTime()+(82*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = child+"="+physics+expires+"; path=/";
}
function readCookie(child) {
var nameEQ = child + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
function eraseCookie(name) {
createCookie(name,"",-1);
}
The cookie is sent between the server and the browser as text, so the cookie value has to be a string, or something that can be converted to a string. When you read the cookie you will get the string back.
If you for example store the value 42 in a cookie, it will be converted to the string representation of the number. When you read the cookie, you will get the string "42" back, so if you want it as a numeric value, you have to parse the string.
The cookie value can be anything you want. You could for example store a user's country selection in a cookie, so that you only have to ask the user once:
createCookie('country', country, true);
Think of it as a key value pair.
You can give your cookie a name and a value. remember you can have multiple cookies, so the name identifies which on you are referring to, and the value...well I guess it stores the value :)
So for instance I have a cookie called "customerId", the value portion could be "bob"
Refer to http://www.w3schools.com/JS/js_cookies.asp