How to Delete all Cookies on my site except for one - javascript

I'm using the following function to clear all cookies, which works.
This is clearing out the PHPSESSID too as far as I can tell. I want to retain just that one cookie alone.
I added the line: if (name == "PHPSESSID") {...
...to try and catch, and skip, altering the cookie names PHPSESSID, but it doesn't catch it for some reason.
Is there a clear reason why it's not catching, or is there a better way to achieve clearing all cookies except for "PHPSESSID"?
The Function:
function clearCookies() {
var cookies = document.cookie.split(";");
for(var i=0; i < cookies.length; i++) {
var equals = cookies[i].indexOf("=");
var name = equals > -1 ? cookies[i].substr(0, equals) : cookies[i];
if (name == "PHPSESSID") {
alert("yes");
}else{
document.cookie = name + "=;expires=Thu, 01 Jan 1970 00:00:00 GMT";
alert(name);
}
}
}

Hi I found the answer by using DevTool's console log instead of the cookie viewer. There's a space in front of PHPSESSID when it's set for some reason. So
" PHPSESSID" works.
Solution here: output it in the console log instead of an alert.

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

Cookies. Append many values in cookies with javascript

I'm sorry for my question, but I don't find any answer.
Is it possible append many values in a single cookie ?
My aim is to create a cookie called ALLINFO, and append in it values such as
name, surname, age, phone etc.
Is it possibile ? Some example please ?
Thank you in advance.
p.s. I work in vs2013 with mvc
You can save a object in the cookie
(function(){
var o = JSON.parse('{"name":"hello","surname":"kc"}');
var e = 'Thu Nov 10 2020 15:44:38';
document.cookie = 'ALLINFO='+ JSON.stringify(o) +';expires=' + e;
})()
For reading the cookie
you can do
function read_cookie(name) {
var result = document.cookie.match(new RegExp(name + '=([^;]+)'));
result && (result = JSON.parse(result[1]));
return result;
}
read_cookie('ALLINFO')

cookies dont work on Chrome

I am using a simple javascript code like this to play around with cookies
var theCookie = "login = ScottPilgrimVStheWorld";
document.cookie=theCookie;
alert(document.cookie);
I have just a simple html page with a body, a header and this javascript code.
Problem is , this is working in IE and FF but not in GC 33.0.1750.154 m. I get an empty alert box. I took a glance at the GC settings and found nothing on blocking/unblocking Cookies. What is happening? Any tips?
Thanks in advance.
EDIT
Here is another function for reading cookies
function getCookie(searchName)
{
var cookies = document.cookie.split(";");
for (var i = 0; i < cookies.length; i++)
{
var cookieCrumbs = cookies[i].split("=");
var cookieName = cookieCrumbs[0];
var cookieValue = cookieCrumbs[1];
if (cookieName == searchName)
{
return cookieValue;
}
}
return false;
}
"The JavaScript Anthology 101 Essential Tips, Tricks & Hacks" by James Edwards and Cameron Adams, Copyright © 2006 SitePoint Pty. Ltd., pp145-146
Try modifying variable theCookie:
var theCookie = "login=ScottPilgrimVStheWorld;";
We must do this because as stated in W3Schools, the template for a cookie is
[cookie-name]=[cookie-name-val]; [Next is optional] expires=[expiry_date].
Also, I don't think you can just get the cookie directly like that. You have to create a function:
function getCookie(cname)
{
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++)
{
var c = ca[i].trim();
if (c.indexOf(name)==0) return c.substring(name.length,c.length);
}
return "";
}
So you change your alert to something like this:
alert(getCookie("login"));
Hope that helped.
No spaces are allowed in the assignment string added to the cookie jar. Try
var theCookie = "login=ScottPilgrimVStheWorld";
Tested on chrome 33 ( 33.0.1750.154 ).
edit:
chris97ong is right in his claim that you need additional logic to extract a single cookie from the cookie jar document.cookie. if you need that, use his code or match against a regex:
var mycookie = document.cookie.replace(/(^|;)login=([^;]+)(;|$)/, "$2");

unable to read cookie first time in javascript

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.

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