How to remove session cookie - javascript

We are trying to clear the cookie details in browser on pressing 'Logout' button with the following code, but the script doesn't remove the session cookie from the browser. But by clearing the session cookies in IE8 browser using developer tool(Tools > Developer Tools >Cache > Clear Session Cookies), the cookies are cleared.
<html:link page="/home.do" onclick="logout();">
<html:img page="/images/logout.jpg"/>
</html:link>
function logout(){
var cookies = document.cookie.split(";");
for (var i = 0; i < cookies.length; i++) {
var cookiename = cookies[i].split("=");
var d = new Date();
d.setDate(d.getDate() - 4);
var expires = ";expires="+d;
var value="";
document.cookie = cookiename + "=" + value + expires + ";";
}
}
How to clear the Session cookies from the browser using script?

if it is httpOnly, then you can not delete it, try modify it from server side

from javascript: Not specifying expiring field, also set value to null, and if it is also hostonly, not specifying domain

If it is a 'session' variable you want to clear...
unset( $_SESSION['YOUR_SESSION_VARIABLE_NAME'] );
This will completely remove this session variable. The title is misleading. The code he shows is not 'session' cookies, they are regular 'cookies'.

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

In JS, I want to check for cookie and if not present, run an animation function and write cookie, and if so, skip animation.

I've already made the animation functions, but I don't want it to animate every time the same person visits the site. So the plan is to check for the cookie and if it is there, skip the intro animation, but if it's not, I want to run the intro animation and create the cookie. I don't know a lot about cookies or Js, so I'm kind of stuck.
This is what I'm using for many projects.
/*-----------------------------------------------------
global function for Set/Get Cookie
------------------------------------------------------*/
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 + ";path=/";
}
function getCookie(name) {
var value = "; " + document.cookie;
var parts = value.split("; " + name + "=");
if (parts.length == 2) return parts.pop().split(";").shift();
}
then set/get like:
SET:
setCookie("c2u", c2u, 365); NOTE: 365 is 365 day
GET:
var cookieSelTimeZone = getCookie("selectedTimeZone");
JavaScript can create, read, and delete cookies with the document.cookie property. U can use any name/key you want like u use in PHP.
You can then read from the cookie property to see if your key/value is set.
More info can be found here

How to Delete all Cookies on my site except for one

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.

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.

Can a userscript delete cookies from a given domain?

Can Greasemonkey delete cookies from a given domain? If so, how?
There are major limitations on what Greasemonkey can delete. Other tools may be better for what you want, see below. But, if all of these conditions are met:
The cookies you want to delete are on the current page's domain.
They are not "Secure cookies".
You loop through the possible paths, including /, a blank path, etc.
No cookies are set by javascript, after the page loads.
The thing tracking you really is a "cookie". Many websites use a variety of other techniques, including LSO's, local storage, etc.
THEN, the following code will delete them:
//--- Loop through cookies and delete them.
var cookieList = document.cookie.split (/;\s*/);
for (var J = cookieList.length - 1; J >= 0; --J) {
var cookieName = cookieList[J].replace (/\s*(\w+)=.+$/, "$1");
eraseCookie (cookieName);
}
Where eraseCookie() is:
(Note that this eraseCookie gets many more cookies by attempting all possible paths and the most likely sub-domains.)
function eraseCookie (cookieName) {
//--- ONE-TIME INITS:
//--- Set possible domains. Omits some rare edge cases.?.
var domain = document.domain;
var domain2 = document.domain.replace (/^www\./, "");
var domain3 = document.domain.replace (/^(\w+\.)+?(\w+\.\w+)$/, "$2");;
//--- Get possible paths for the current page:
var pathNodes = location.pathname.split ("/").map ( function (pathWord) {
return '/' + pathWord;
} );
var cookPaths = [""].concat (pathNodes.map ( function (pathNode) {
if (this.pathStr) {
this.pathStr += pathNode;
}
else {
this.pathStr = "; path=";
return (this.pathStr + pathNode);
}
return (this.pathStr);
} ) );
( eraseCookie = function (cookieName) {
//--- For each path, attempt to delete the cookie.
cookPaths.forEach ( function (pathStr) {
//--- To delete a cookie, set its expiration date to a past value.
var diagStr = cookieName + "=" + pathStr + "; expires=Thu, 01-Jan-1970 00:00:01 GMT;";
document.cookie = diagStr;
document.cookie = cookieName + "=" + pathStr + "; domain=" + domain + "; expires=Thu, 01-Jan-1970 00:00:01 GMT;";
document.cookie = cookieName + "=" + pathStr + "; domain=" + domain2 + "; expires=Thu, 01-Jan-1970 00:00:01 GMT;";
document.cookie = cookieName + "=" + pathStr + "; domain=" + domain3 + "; expires=Thu, 01-Jan-1970 00:00:01 GMT;";
} );
} ) (cookieName);
}
Optional function, for information or debug:
function listCookies () {
var cookieList = document.cookie.split (/;\s*/);
for (var J = 0, numCookies = cookieList.length; J < numCookies; ++J) {
console.log ("Cookie ", J, ": ", cookieList[J]);
}
}
Your GM script can also use iFrame tricks to delete cookies on third-party domains, but GM is not the best way to handle cookies, in general.
Don't be fooled by any other claims, Greasemonkey and javascript simply cannot delete a cookie unless all of the conditions, listed at the top of this answer, are met. Note that javascript and Greasemonkey cannot even see all the cookies on a page.
Greasemonkey is not the best tool for this, although it may be adequate for select situations.
Here are some far more powerful solutions:
Use Selective Cookie Delete. It keeps the cookies you want and deletes the rest. It does this at the push of a very handy button or automatically when Firefox closes. Both white-lists and black-lists are supported.
Use BetterPrivacy for sneakier LSO's.
Run CCleaner at least once a week, to exorcise a broad spectrum of tracking and cruft.
For powerful, custom, fully-automated cookie removal that does not have the severe limitations that Greasemonkey has, and that runs more often than Selective Cookie Delete, you can write your own browser extension.
You should be able to delete cookies for the currently open site. Have a look at the Cookie Zapper script, this may do what you want and if not the source will probably point you in the right direction.

Categories

Resources