Javascript Cookie Value defined - javascript

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

Related

Browser cookie storage

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

Storing and Retrieving a JSON Obj from a Cookie

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.

What is the purpose of while and for loops, if statement in this code?

I'm trying to understand the concept of Cookies in JavaScript. For that, I'm trying to understand the working of this code from http://www.w3schools.com/js/tryit.asp?filename=tryjs_cookie_username:
<script>
function setCookie(cname,cvalue,exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires=" + d.toGMTString();
document.cookie = cname+"="+cvalue+"; "+expires;
}
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 user=getCookie("username");
if (user != "") {
alert("Welcome again " + user);
} else {
user = prompt("Please enter your name:","");
if (user != "" && user != null) {
setCookie("username", user, 30);
}
}
}
</script>
I've understood most of the things in this code, but still I have some doubts/queries (in getCookie function):
Doubt 1. Purpose of for loop
Doubt 2. Purpose of if
Doubt 3. Purpose of while loop
Doubt 4. Purpose of return "";
I'm asking about these because the script is running fine even without using these conditions. (I know the working of each inbuilt function in getCookie function. I just don't understand the use of above loops and conditions).
Here's what I want to say:
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
var c = ca[0];
return c.substring(name.length, c.length);
}
Even after I've changed the expiry date to a past date in setCookie function (exdays*2000), it is still displaying "Welcome to XYZ" message. That means Cookie is not deleted. But when I run the same code in a different browser, it is deleted. Why is so?
Doubt 1. Purpose of for loop
All cookies are saved as a semicolon separated key-value (actually it is semicolon and space ;). key and values are separated by equal-to (=) symbol. By iterating, you are checking all the keys and returning only the value of key which is matching the argument passed to the method
Doubt 2. Purpose of if
To check if the current key from the iteration contains the cookie name that is passed to the method.
Doubt 3. Purpose of while loop
To remove all spaces one by one. Actually this one can easily be improved by using trim() method.
//while (c.charAt(0)==' ') c = c.substring(1);
c = c.trim();
Doubt 4. Purpose of return "";
if there is no value found, then return an empty string rather than user having to check for the null or undefined.
Even after I've changed the expiry date to a past date in setCookie
function (exdays*2000), it is still displaying "Welcome to XYZ"
message. That means Cookie is not deleted. But when I run the same
code in a different browser, it is deleted. Why is so?
It is possible (assuming this, since you have not shared any fiddle) that your setCookie method is not executed when you opened that page second time on the same browser.
Doubt 1. Purpose of for loop
Cookies are stored as a single line string like this:
"Cookie_1=Cookie_value1; Cookie_2=Cookie_value2; Cookie_3=Cookie_value3; Cookie_4=Cookie_value4;"
Then this is split into arrays with
var ca = document.cookie.split(';');
So the value of ca is now ["Cookie_1=Cookie_value1"," Cookie_2=Cookie_value2"," Cookie_3=Cookie_value3"," Cookie_4=Cookie_value4",""]
which can be considered a cookie "entity" for each member of the array
Doubt 3. Purpose of while loop
If you look at the values in the ca array, you will see that Cookie 2 has a value of " Cookie_2=Cookie_value2". There are leading spaces that we need to trim out so there goes the purpose of this while loop
while (c.charAt(0)==' ') c = c.substring(1);
Doubt 2. Purpose of if
After the leading spaces are trimmed then you can check if the cookie name matches the one you are looking for.
For example, "Cookie_3=Cookie_value3".indexOf("Cookie_3=") is equal to 0
Doubt 4. Purpose of return "";
This is just the default value to return if the cookie name specified is not found, something like a case default in switch case.

Removing Cookie value from browser

I know that this has been asked many times, and ive tried using the accepted answers. But sadly none of that seems to work for me in my browser(Mozilla v18.0.2).
I am using backbone for my website and im using cookies to handle user login sessions.
The following are the unsuccessful ones :
Code 1
var cookie_date = new Date ( ); // now
cookie_date.setTime ( cookie_date.getTime() - 1 ); // one second before now.
// empty cookie's value and set the expiry date to a time in the past.
document.cookie = "uid=;expires=" + cookie_date.toGMTString();
document.cookie = "userName=;expires=" + cookie_date.toGMTString();
Code 2
var nameEQ = name + "=";
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){
uid = c.substring(nameEQ.length,c.length);
return uid;
}
};
Any working solution for removing browser cookies??
Thanks
Roy
Simple answer
You can't.
Long answer
You can overwrite the cookie and give it an expiration time in the past.
Browsers will discard it at some point after its expiration. Until then you need to check yourself, if it has been “deleted”, e. g. with a special value or by comparing the expiration date with the current time.

Why isn't my cookie being set?

I am learning, please be kind if it is an obvious mistake.
/*set cookie*/
function setCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}
function readCookie(name) {
var nameEQ = name + "=";
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) {
setCookie(name,"",-1);
}
$(window).load(function() {
//check for the cookie
var language = readCookie('language');
//if null show red
if (language!=null)
{
$('.blue').hide();
alert('No cookie set');
}
//if null show red
else if (language!=red)
{
$('.blue').hide();
alert('The cookie is red');
}
//if blue show blue
else {
$('.red').hide();
alert('The cookie is set to blue');
}
$('#blue').click(function() {
$('.red').hide();
$('.blue').show();
setCookie('language','blue', 30);
alert('The cookie is set to blue');
});
$('#red').click(function() {
$('.red').show();
$('.blue').hide();
setCookie('language','red', 30);
alert('The cookie is set to red');
});
});
Thank-you.
Learning to use Firebug is the best advice. Another helpful tool is a colorizing editor. Even SO provides a little help of this kind. Note the line:
else if (language!=red)
"red" wasn't colored as a string, so it stood out by not standing out. Is there a variable named "red" defined somewhere in the original code? If not, this compares language to undefined.
Also, consider the lines that follow this statement:
else if (language!='red') {
$('.blue').hide();
alert('The cookie is red');
You just tested that the cookie value was not red, but you alert that it is. You make a similar mistake on the first test:
if (language!=null) {
$('.blue').hide();
alert('No cookie set');
language is not null, but the message you display suggests it is.
This isn't related to your question, but there are some simplifications you can make. For one, jQuery defines a trim method on String to remove leading and trailing whitespace. Make use if this in readCookie rather than the while (c.charAt(0)==' ') loop.
Another improvement is that the current technique of choosing an element to show by using a sequence of if blocks doesn't scale well. Your homework is to use string operations and whatnot to better handle an arbitrary number of elements, then add ".green", ".yellow", ".magenta" and ".cyan" elements. You might need to change the default behavior from showing all .color elements to hiding them. Using objects as associative arrays may also be helpful.
If you're learning the best answer to your question here would probably be some debugging tips. What are you using for debugging?
Have you tried Firebug in Firefox. http://getfirebug.com/ This will let you step through your code one line at a time and inspect exactly what it is doing, what values are really being passed to functions, and exactly what string you are assigning to document.cookie.

Categories

Resources