How do I set and unset a cookie using jQuery, for example create a cookie named test and set the value to 1?
Update April 2019
jQuery isn't needed for cookie reading/manipulation, so don't use the original answer below.
Go to https://github.com/js-cookie/js-cookie instead, and use the library there that doesn't depend on jQuery.
Basic examples:
// Set a cookie
Cookies.set('name', 'value');
// Read the cookie
Cookies.get('name') => // => 'value'
See the docs on github for details.
Before April 2019 (old)
See the plugin:
https://github.com/carhartl/jquery-cookie
You can then do:
$.cookie("test", 1);
To delete:
$.removeCookie("test");
Additionally, to set a timeout of a certain number of days (10 here) on the cookie:
$.cookie("test", 1, { expires : 10 });
If the expires option is omitted, then the cookie becomes a session cookie and is deleted when the browser exits.
To cover all the options:
$.cookie("test", 1, {
expires : 10, // Expires in 10 days
path : '/', // The value of the path attribute of the cookie
// (Default: path of page that created the cookie).
domain : 'jquery.com', // The value of the domain attribute of the cookie
// (Default: domain of page that created the cookie).
secure : true // If set to true the secure attribute of the cookie
// will be set and the cookie transmission will
// require a secure protocol (defaults to false).
});
To read back the value of the cookie:
var cookieValue = $.cookie("test");
UPDATE (April 2015):
As stated in the comments below, the team that worked on the original plugin has removed the jQuery dependency in a new project (https://github.com/js-cookie/js-cookie) which has the same functionality and general syntax as the jQuery version. Apparently the original plugin isn't going anywhere though.
There is no need to use jQuery particularly to manipulate cookies.
From QuirksMode (including escaping characters)
function createCookie(name, value, days) {
var expires;
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = "; expires=" + date.toGMTString();
} else {
expires = "";
}
document.cookie = encodeURIComponent(name) + "=" + encodeURIComponent(value) + expires + "; path=/";
}
function readCookie(name) {
var nameEQ = encodeURIComponent(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 decodeURIComponent(c.substring(nameEQ.length, c.length));
}
return null;
}
function eraseCookie(name) {
createCookie(name, "", -1);
}
Take a look at
How do I remove an existing class name and add a new one with jQuery and cookies?
<script type="text/javascript">
function setCookie(key, value, expiry) {
var expires = new Date();
expires.setTime(expires.getTime() + (expiry * 24 * 60 * 60 * 1000));
document.cookie = key + '=' + value + ';expires=' + expires.toUTCString();
}
function getCookie(key) {
var keyValue = document.cookie.match('(^|;) ?' + key + '=([^;]*)(;|$)');
return keyValue ? keyValue[2] : null;
}
function eraseCookie(key) {
var keyValue = getCookie(key);
setCookie(key, keyValue, '-1');
}
</script>
You can set the cookies as like
setCookie('test','1','1'); //(key,value,expiry in days)
You can get the cookies as like
getCookie('test');
And finally you can erase the cookies like this one
eraseCookie('test');
Hope it will helps to someone :)
EDIT:
If you want to set the cookie to all the path/page/directory then set path attribute to the cookie
function setCookie(key, value, expiry) {
var expires = new Date();
expires.setTime(expires.getTime() + (expiry * 24 * 60 * 60 * 1000));
document.cookie = key + '=' + value + ';path=/' + ';expires=' + expires.toUTCString();
}
Thanks,
vicky
You can use a plugin available here..
https://plugins.jquery.com/cookie/
and then to write a cookie do
$.cookie("test", 1);
to access the set cookie do
$.cookie("test");
Here is my global module I use -
var Cookie = {
Create: function (name, value, days) {
var expires = "";
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = "; expires=" + date.toGMTString();
}
document.cookie = name + "=" + value + expires + "; path=/";
},
Read: function (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;
},
Erase: function (name) {
Cookie.create(name, "", -1);
}
};
Make sure not to do something like this:
var a = $.cookie("cart").split(",");
Then, if the cookie doesn't exist, the debugger will return some unhelpful message like ".cookie not a function".
Always declare first, then do the split after checking for null. Like this:
var a = $.cookie("cart");
if (a != null) {
var aa = a.split(",");
Here is how you set the cookie with JavaScript:
below code has been taken from https://www.w3schools.com/js/js_cookies.asp
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=/";
}
now you can get the cookie with below function:
function getCookie(cname) {
var name = cname + "=";
var decodedCookie = decodeURIComponent(document.cookie);
var ca = decodedCookie.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 "";
}
And finally this is how you check the cookie:
function checkCookie() {
var username = getCookie("username");
if (username != "") {
alert("Welcome again " + username);
} else {
username = prompt("Please enter your name:", "");
if (username != "" && username != null) {
setCookie("username", username, 365);
}
}
}
If you want to delete the cookie just set the expires parameter to a passed date:
document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";
A simple example of set cookie in your browser:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>jquery.cookie Test Suite</title>
<script src="jquery-1.9.0.min.js"></script>
<script src="jquery.cookie.js"></script>
<script src="JSON-js-master/json.js"></script>
<script src="JSON-js-master/json_parse.js"></script>
<script>
$(function() {
if ($.cookie('cookieStore')) {
var data=JSON.parse($.cookie("cookieStore"));
$('#name').text(data[0]);
$('#address').text(data[1]);
}
$('#submit').on('click', function(){
var storeData = new Array();
storeData[0] = $('#inputName').val();
storeData[1] = $('#inputAddress').val();
$.cookie("cookieStore", JSON.stringify(storeData));
var data=JSON.parse($.cookie("cookieStore"));
$('#name').text(data[0]);
$('#address').text(data[1]);
});
});
</script>
</head>
<body>
<label for="inputName">Name</label>
<br />
<input type="text" id="inputName">
<br />
<br />
<label for="inputAddress">Address</label>
<br />
<input type="text" id="inputAddress">
<br />
<br />
<input type="submit" id="submit" value="Submit" />
<hr>
<p id="name"></p>
<br />
<p id="address"></p>
<br />
<hr>
</body>
</html>
Simple just copy/paste and use this code for set your cookie.
You can use the library on Mozilla website here
You'll be able to set and get cookies like this
docCookies.setItem(name, value);
docCookies.getItem(name);
I think Fresher gave us nice way, but there is a mistake:
<script type="text/javascript">
function setCookie(key, value) {
var expires = new Date();
expires.setTime(expires.getTime() + (value * 24 * 60 * 60 * 1000));
document.cookie = key + '=' + value + ';expires=' + expires.toUTCString();
}
function getCookie(key) {
var keyValue = document.cookie.match('(^|;) ?' + key + '=([^;]*)(;|$)');
return keyValue ? keyValue[2] : null;
}
</script>
You should add "value" near getTime(); otherwise the cookie will expire immediately :)
Reducing the number of operations compared to previous answers, I use the following.
function setCookie(name, value, expiry) {
let d = new Date();
d.setTime(d.getTime() + (expiry*86400000));
document.cookie = name + "=" + value + ";" + "expires=" + d.toUTCString() + ";path=/";
}
function getCookie(name) {
let cookie = document.cookie.match('(^|;) ?' + name + '=([^;]*)(;|$)');
return cookie ? cookie[2] : null;
}
function eatCookie(name) {
setCookie(name, "", -1);
}
I thought Vignesh Pichamani's answer was the simplest and cleanest. Just adding to his the ability to set the number of days before expiration:
EDIT: also added 'never expires' option if no day number is set
function setCookie(key, value, days) {
var expires = new Date();
if (days) {
expires.setTime(expires.getTime() + (days * 24 * 60 * 60 * 1000));
document.cookie = key + '=' + value + ';expires=' + expires.toUTCString();
} else {
document.cookie = key + '=' + value + ';expires=Fri, 30 Dec 9999 23:59:59 GMT;';
}
}
function getCookie(key) {
var keyValue = document.cookie.match('(^|;) ?' + key + '=([^;]*)(;|$)');
return keyValue ? keyValue[2] : null;
}
Set the cookie:
setCookie('myData', 1, 30); // myData=1 for 30 days.
setCookie('myData', 1); // myData=1 'forever' (until the year 9999)
I know there are many great answers. Often, I only need to read cookies and I do not want to create overhead by loading additional libraries or defining functions.
Here is how to read cookies in one line of javascript. I found the answer in Guilherme Rodrigues' blog article:
('; '+document.cookie).split('; '+key+'=').pop().split(';').shift()
This reads the cookie named key, nice, clean and simple.
Try (doc here, SO snippet not works so run this one)
document.cookie = "test=1" // set
document.cookie = "test=1;max-age=0" // unset
Background
Cookies were originally invented by Netscape to give 'memory' to web servers and browsers. The HTTP protocol, which arranges for the transfer of web pages to your browser and browser requests for pages to servers, is state-less, which means that once the server has sent a page to a browser requesting it, it doesn't remember a thing about it. So if you come to the same web page a second, third, hundredth or millionth time, the server once again considers it the very first time you ever came there.
This can be annoying in a number of ways. The server cannot remember if you identified yourself when you want to access protected pages, it cannot remember your user preferences, it cannot remember anything. As soon as personalization was invented, this became a major problem.
Cookies were invented to solve this problem. There are other ways to solve it, but cookies are easy to maintain and very versatile.
How cookies work
A cookie is nothing but a small text file that's stored in your browser. It contains some data:
A name-value pair containing the actual data
An expiry date after which it is no longer valid
The domain and path of the server it should be sent to
Example
To set or unset cookies using Javascript, you can do the following:
// Cookies
function createCookie(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 setCookie(name, days) {
createCookie(name, name, days);
}
function unsetCookie(name) {
createCookie(name, "", -1);
}
You can access like below,
setCookie("demo", 1); // to set new cookie
readCookie("demo"); // to retrive data from cookie
unsetCookie("demo"); // will unset that cookie
The following code will remove all cookies within the current domain and all trailing subdomains (www.some.sub.domain.com, .some.sub.domain.com, .sub.domain.com and so on.).
A single line vanilla JS version (no need for jQuery):
document.cookie.replace(/(?<=^|;).+?(?=\=|;|$)/g, name => location.hostname.split('.').reverse().reduce(domain => (domain=domain.replace(/^\.?[^.]+/, ''),document.cookie=`${name}=;max-age=0;path=/;domain=${domain}`,domain), location.hostname));
This is a readable version of this single line:
document.cookie.replace(
/(?<=^|;).+?(?=\=|;|$)/g,
name => location.hostname
.split(/\.(?=[^\.]+\.)/)
.reduceRight((acc, val, i, arr) => i ? arr[i]='.'+val+acc : (arr[i]='', arr), '')
.map(domain => document.cookie=`${name}=;max-age=0;path=/;domain=${domain}`)
);
I know, there are plenty of answers already, but here's one that has set, get, and delete all beautifully vanilla and nicely put into a global reference:
window.cookieMonster = window.cookieMonster ||
{
// https://stackoverflow.com/a/25490531/1028230
get: function (cookieName) {
var b = document.cookie.match('(^|;)\\s*' + cookieName + '\\s*=\\s*([^;]+)');
return b ? b.pop() : '';
},
delete: function (name) {
document.cookie = '{0}=; Path=/; Expires=Thu, 01 Jan 1970 00:00:01 GMT;'
.replace('{0}', name);
},
set: function (name, value) {
document.cookie =
'{0}={1};expires=Fri, 31 Dec 9999 23:59:59 GMT;path=/;SameSite=Lax'
.replace('{0}', name)
.replace('{1}', value);
}
};
Notice cookie getting regex was taken from this answer to a question in another castle.
And let's test:
cookieMonster.set('chocolate', 'yes please');
cookieMonster.set('sugar', 'that too');
console.log(cookieMonster.get('chocolate'));
console.log(document.cookie);
cookieMonster.delete('chocolate');
console.log(cookieMonster.get('chocolate'));
console.log(document.cookie);
If you didn't have any cookies before trying, should give you...
yes please
chocolate=yes please; sugar=that too
sugar=that too
Notice the cookies last not quite heat-death-of-the-universe long, but essentially that from our perspective. You can figure out how to change dates pretty easily from looking at the strings here or from other answers.
How to use it?
//To set a cookie
$.cookie('the_cookie', 'the_value');
//Create expiring cookie, 7 days from then:
$.cookie('the_cookie', 'the_value', { expires: 7 });
//Create expiring cookie, valid across entire page:
$.cookie('the_cookie', 'the_value', { expires: 7, path: '/' });
//Read cookie
$.cookie('the_cookie'); // => 'the_value'
$.cookie('not_existing'); // => null
//Delete cookie by passing null as value:
$.cookie('the_cookie', null);
// Creating cookie with all availabl options
$.cookie('myCookie2', 'myValue2', { expires: 7, path: '/', domain: 'example.com',
secure: true, raw: true });
Available Options:
expires: Define lifetime of the cookie. Value can be a Number (which will be interpreted as days from time of creation) or a Date object. If omitted, the cookie is a session cookie.
path: Define the path where cookie is valid. By default the path of the cookie is the path of the page where the cookie was created (standard browser behavior). If you want to make it available for instance across the entire page use path: '/'.
domain: Domain of page where the cookie was created.
secure: Default: false. If true, the cookie transmission requires a secure protocol (https).
raw: By default the cookie is encoded/decoded when creating/reading, using encodeURIComponent/ decodeURIComponent. Turn off by setting raw: true.
Related
I'm trying to create a session cookie for my media player here in order to track usage and other things the code and the code snippet below isn't creating it at all, (by the way, i'm using one script to create multiple cookies using parameters and want to keep it like that to prevent lengthily scripts)
I've tried a lot of the answers provided in the website already but they don't work, they just result in the same problem
//script to create the cookies
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=/";
}
//for the cookie that makes the name, not part of the question
function getCookie(cname) {
var name = cname + "=";
var decodedCookie = decodeURIComponent(document.cookie);
var ca = decodedCookie.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 "";
}
// also for the name
function checkCookie() {
var user=getCookie("username");
if (user != "") {
document.getElementById("display").innerHTML = "Welcome back " + user
} else {
document.getElementById("display").innerHTML = "Please enter your name in The prompt at the top of your screen!";
user = prompt("Please enter your name:","");
if (user != "" && user != null) {
setCookie("username", user, 30);
}
}
}
window.onload = checkCookie()
//for the session
window.onload = createsession()
function createsession(length){
var sessionnumber = Random rand = new Random();
long drand = (long)(rand.nextDouble()*10000000000L);
setCookie("session", sessionnumber);
};
window.onbeforeunload = function(){
document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";
};
what I want is for the script to create a cookie that expires at end of the browser session, while being able to keep the other scripts the same to allow me to create multiple cookies without making duplicates of those processing scripts
I created the following fiddle for testing: https://jsfiddle.net/Twisty/toxjLmd8/10/
I added a few things to increase info in console. When I inspect the page and view Storage I can see session cookie and username cookie. If I refresh, I am prompted to enter name again. So it seems to be working as expected.
$(function() {
function setCookie(cname, cvalue, exdays) {
var d = new Date();
if (exdays == undefined) {
exdays = 1;
}
d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
var expires = "expires=" + d.toGMTString();
console.log("Set Cookie: " + cname + "=" + cvalue, expires);
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}
function getCookie(cname) {
var name = cname + "=";
var decodedCookie = decodeURIComponent(document.cookie);
var ca = decodedCookie.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 false;
}
function checkCookie() {
var user = getCookie("username");
if (user != "") {
$("#display").html("Welcome back " + user);
} else {
$("#display").html("Welcome, please enter your name.");
user = prompt("Please enter your name:", "");
if (user != "" && user != null) {
setCookie("username", user, 30);
}
}
}
function newSession() {
var sessionnumber = Math.random() * 10000000000.0;
console.log("New Session: " + sessionnumber);
setCookie("session", sessionnumber, 0.0125);
}
function checkSession() {
if (getCookie("session") == false) {
newSession();
}
console.log("Current Session: " + getCookie("session"));
}
window.onbeforeunload = function() {
console.log("Closing - Expire 'username' Cookie");
setCookie("username", "", 0);
};
window.onload = checkCookie();
window.onload = checkSession();
});
Setting a past date or current date and time should have the browser expire the cookie right away and drop it. Setting a cookie with no expiration date can have unexpected results from different browsers. If the date is not set it should expire at the end of the session (the expected behavior) yet the browser may see that it has already expired (still good) or will never expire (really not good). Not all browsers are written the same.
Also if onbeforeunload callback is not triggered, the cookie is not expired but would remain active for 30 days per checkCookie(). You could set the cookie to expire in 20 min (0.0125 days). This is how sessions are handled on the server-side. If the socket closes and the session is idle for 20 min (the default for Session Idle Timeout), the session data is dropped.
Hope this helps.
I'm a bit stuck on some javascript. So the script below sets eith one of two cookies.
If the page contains 'lpt' and a cookie called organic doesn't exist (not sure if the second part actually works) then create a cookie. Otherwise create a different one.
Problem is which ever cookie is created needs to be held and not swap them out? ie if the first one is created don't ever create the other one.
if(document.URL.indexOf("lpt") >= 0 && document.cookie.indexOf("organic") < 0){
document.cookie = "ppc_campaign=this will be the url; expires=Thu, 18 Dec 2018 12:00:00 UTC; path=/";
}
else {
document.cookie = "organic=this will be the url; expires=Thu, 18 Dec 2013 12:00:00 UTC; path=/";
}
You dont want to dublicate the cooke if it is already created
set expiry date for almost 10years, 2050 or 2030 Then use this function to find if cookie already exists
document.cookie.search('cookie')
if this function returns -1
then save your cookie
may be this function will help you to find your cookie in easiest way just passing your name of cookie... you can modify according to your logic
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(cookiename) {
var user = getCookie(cookiename);//cookiename="username"
if (user != "") {
alert("Welcome again " + user);
} else {
user = prompt("Please enter your name:", "");
if (user != "" && user != null) {
setCookie("username", user, 365);
}
}
}
Is my function of creating a cookie correct? How do I delete the cookie at the beginning of my program? is there a simple coding?
function createCookie(name,value,days)
function setCookie(c_name,value,1) {
document.cookie = c_name + "=" +escape(value);
}
setCookie('cookie_name',mac);
function eraseCookie(c_name) {
createCookie(cookie_name,"",-1);
}
Try this:
function delete_cookie( name, path, domain ) {
if( get_cookie( name ) ) {
document.cookie = name + "=" +
((path) ? ";path="+path:"")+
((domain)?";domain="+domain:"") +
";expires=Thu, 01 Jan 1970 00:00:01 GMT";
}
}
You can define get_cookie() like this:
function get_cookie(name){
return document.cookie.split(';').some(c => {
return c.trim().startsWith(name + '=');
});
}
Here a good link on Quirksmode.
function setCookie(name,value,days) {
var expires = "";
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days*24*60*60*1000));
expires = "; expires=" + date.toUTCString();
}
document.cookie = name + "=" + (value || "") + expires + "; path=/";
}
function getCookie(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) {
document.cookie = name+'=; Max-Age=-99999999;';
}
would this work?
function eraseCookie(name) {
document.cookie = name + '=; Max-Age=0'
}
I know Max-Age causes the cookie to be a session cookie in IE when creating the cookie. Not sure how it works when deleting cookies.
Some of the other solutions might not work if you created the cookie manually.
Here's a quick way to delete a cookie:
document.cookie = 'COOKIE_NAME=; Max-Age=0; path=/; domain=' + location.host;
If this doesn't work, try replacing location.host with location.hostname in the snippet above.
Here is an implementation of a delete cookie function with unicode support from Mozilla:
function removeItem(sKey, sPath, sDomain) {
document.cookie = encodeURIComponent(sKey) +
"=; expires=Thu, 01 Jan 1970 00:00:00 GMT" +
(sDomain ? "; domain=" + sDomain : "") +
(sPath ? "; path=" + sPath : "");
}
removeItem("cookieName");
If you use AngularJs, try $cookies.remove (underneath it uses a similar approach):
$cookies.remove('cookieName');
You can do this by setting the date of expiry to yesterday.
Setting it to "-1" doesn't work. That marks a cookie as a Sessioncookie.
To delete a cookie I set it again with an empty value and expiring in 1 second.
In details, I always use one of the following flavours (I tend to prefer the second one):
1.
function setCookie(key, value, expireDays, expireHours, expireMinutes, expireSeconds) {
var expireDate = new Date();
if (expireDays) {
expireDate.setDate(expireDate.getDate() + expireDays);
}
if (expireHours) {
expireDate.setHours(expireDate.getHours() + expireHours);
}
if (expireMinutes) {
expireDate.setMinutes(expireDate.getMinutes() + expireMinutes);
}
if (expireSeconds) {
expireDate.setSeconds(expireDate.getSeconds() + expireSeconds);
}
document.cookie = key +"="+ escape(value) +
";domain="+ window.location.hostname +
";path=/"+
";expires="+expireDate.toUTCString();
}
function deleteCookie(name) {
setCookie(name, "", null , null , null, 1);
}
Usage:
setCookie("reminder", "buyCoffee", null, null, 20);
deleteCookie("reminder");
2
function setCookie(params) {
var name = params.name,
value = params.value,
expireDays = params.days,
expireHours = params.hours,
expireMinutes = params.minutes,
expireSeconds = params.seconds;
var expireDate = new Date();
if (expireDays) {
expireDate.setDate(expireDate.getDate() + expireDays);
}
if (expireHours) {
expireDate.setHours(expireDate.getHours() + expireHours);
}
if (expireMinutes) {
expireDate.setMinutes(expireDate.getMinutes() + expireMinutes);
}
if (expireSeconds) {
expireDate.setSeconds(expireDate.getSeconds() + expireSeconds);
}
document.cookie = name +"="+ escape(value) +
";domain="+ window.location.hostname +
";path=/"+
";expires="+expireDate.toUTCString();
}
function deleteCookie(name) {
setCookie({name: name, value: "", seconds: 1});
}
Usage:
setCookie({name: "reminder", value: "buyCoffee", minutes: 20});
deleteCookie("reminder");
For people who just want 1 line of code to delete a cookie:
If you created a cookie, for example in a web browser console with document.cookie = "test=hello"
You can delete it with:
document.cookie = "test=;expires=" + new Date(0).toUTCString()
Or if you prefer to write the UTC date directly:
document.cookie = "test=;expires=Thu, 01 Jan 1970 00:00:00 GMT"
If you are on a different path than the cookie (for example if you want to delete a cookie that is used on all paths), you can add path=/; after test=; and if you are on a different domain (for example when a cookie is set for all subdomains by using .example.com instead of www.example.com), you can add domain=.example.com; after test=;.
Update: instead of expires=..., using Max-Age=0 like in other answers works also (tested with Firefox).
I had trouble deleting a cookie made via JavaScript and after I added the host it worked (scroll the code below to the right to see the location.host). After clearing the cookies on a domain try the following to see the results:
if (document.cookie.length==0)
{
document.cookie = 'name=example; expires='+new Date((new Date()).valueOf()+1000*60*60*24*15)+'; path=/; domain='+location.host;
if (document.cookie.length==0) {alert('Cookies disabled');}
else
{
document.cookie = 'name=example; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/; domain='+location.host;
if (document.cookie.length==0) {alert('Created AND deleted cookie successfully.');}
else {alert('document.cookies.length = '+document.cookies.length);}
}
}
I use this on my websites that works on Chrome and Firefox.
function delete_cookie(name) { document.cookie = name +'=; Path=/; Domain=' + location.host + '; Expires=Thu, 01 Jan 1970 00:00:01 GMT; SameSite=None; Secure' }
if ("JSESSIONID".equals(cookie.getName()) || "LtpaToken2".equals(cookie.getName())) {
cookie.setValue("");
cookie.setPath("/");
cookie.setMaxAge(0);
cookie.setHttpOnly(true);
response.addCookie(cookie);
}
I used to generate the cookie from backend and redirect to frontend. The only way I got it working has been to set the expires date in the past in the backned and redirect back on frontend
We don't have the ability to delete cookies in JavaScript, so to delete it we need to create another cookie with an earlier date.
Set Cookie
let expires = null
const cookieName = 'userlogin'
const d = new Date();
d.setTime(d.getTime() + 2 * 24 * 60 * 60 * 1000);
document.cookie = cookieName + "=" + value+ ";" + expires + ";path=/";
Delete Cookie
let expires = null
const d = new Date();
d.setTime(d.getTime() - 2 * 24 * 60 * 60 * 1000);
expires = "expires=" + d.toUTCString();
document.cookie = 'userlogin' + "=" + value+ ";" + expires + ";path=/";
Hi i am trying to make code for clear cookies in jquery onclick of logout button but didn't get solution
function logout()
{
document.cookie = 'Visit=; expires='+new Date(0).toUTCString() +'; path=/FinalVertozz/';
window.location='../login.html';
}
cookies details
Name: Visit
Content: 09850227123455130
Domain: localhost
Path: /FinalVertozz
Send for: Any kind of connection
Accessible to script: Yes
Created: Saturday, October 4, 2014 11:25:45 AM
Expires: When the browsing session ends
Can you use simple javascript. It's easy.
function ClearCookies()
{
var cookiesCollection = document.cookie.split(";");
for (var i = 0; i < cookiesCollection .length; i++)
{
var cookieName = cookiesCollection [i];
var pos= cookieName.indexOf("=");
var name = pos> -1 ? cookieName.substr(0, pos) : cookieName;
document.cookie = name + "=;expires=Thu, 01 Jan 1970 00:00:00 GMT";
}
}
From the reference of this question and answer from #Russ Cam
How do I set/unset cookie with jQuery?
Use this function to reuse
function createCookie(name, value, days) {
var expires;
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = "; expires=" + date.toGMTString();
} else {
expires = "";
}
document.cookie = escape(name) + "=" + escape(value) + expires + "; path=/";
}
function readCookie(name) {
var nameEQ = escape(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 unescape(c.substring(nameEQ.length, c.length));
}
return null;
}
function eraseCookie(name) {
createCookie(name, "", -1);
}
Hope it may help :)
This issue is the path. If you remove it things will work.
document.cookie = 'Visit=; expires='+new Date(0).toUTCString();
Also, you're not using any jQuery in the above example. The question may be better stated as "remove cookies in JavaScript on logout button".
I would like to be able to show a user a picture from one form page to the next. The picture will be dynamic based on what he or she is doing. So, I need to store the path link to that image in a cookie and then load that image on the next page.
How do I do that?
Check the plugin: https://github.com/carhartl/jquery-cookie
and then do:
$.cookie("img", img_url);
[OR]
You can set and get cookie using these functions: (From Quirksmode)
function createCookie(name, value, days) {
var expires;
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = "; expires=" + date.toGMTString();
} else {
expires = "";
}
document.cookie = escape(name) + "=" + escape(value) + expires + "; path=/";
}
function readCookie(name) {
var nameEQ = escape(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 unescape(c.substring(nameEQ.length, c.length));
}
return null;
}
Use document.cookie to set and get the image URLs.
check this cite for details: w3Schools
It shows that you didn't do much research on this simple thing.
Here's a very simple JSFiddle: fiddle
// Assign the cookie
document.cookie = "imgpath=/your/image.png";
alert(document.cookie);
// Use a regular expression to get the path from the entire cookie string. Sanitizations are left up to you.
var imgPath = /imgpath=([^;]+)/i.exec(document.cookie)[1];
alert(imgPath);
I suggest using the jQuery.cookie plugin mentioned in the other answers though, no need to make it any harder than it already is.
Here is the regular expression explained: http://regex101.com/r/qH6rB5/1 - it shows how the actual value you are interested in, is captured.