How to pass variables from one file to another? [duplicate] - javascript

How can I create and read a value from a cookie in JavaScript?

Here are functions you can use for creating and retrieving cookies.
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 = name + "=" + value + expires + "; path=/";
}
function getCookie(c_name) {
if (document.cookie.length > 0) {
c_start = document.cookie.indexOf(c_name + "=");
if (c_start != -1) {
c_start = c_start + c_name.length + 1;
c_end = document.cookie.indexOf(";", c_start);
if (c_end == -1) {
c_end = document.cookie.length;
}
return unescape(document.cookie.substring(c_start, c_end));
}
}
return "";
}

Minimalistic and full featured ES6 approach:
const setCookie = (name, value, days = 7, path = '/') => {
const expires = new Date(Date.now() + days * 864e5).toUTCString()
document.cookie = name + '=' + encodeURIComponent(value) + '; expires=' + expires + '; path=' + path
}
const getCookie = (name) => {
return document.cookie.split('; ').reduce((r, v) => {
const parts = v.split('=')
return parts[0] === name ? decodeURIComponent(parts[1]) : r
}, '')
}
const deleteCookie = (name, path) => {
setCookie(name, '', -1, path)
}

JQuery Cookies
or plain Javascript:
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;
}
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);
}
}
}

ES7, using a regex for get(). Based on MDN
const Cookie = {
get: name => {
let c = document.cookie.match(`(?:(?:^|.*; *)${name} *= *([^;]*).*$)|^.*$`)[1]
if (c) return decodeURIComponent(c)
},
set: (name, value, opts = {}) => {
/*If options contains days then we're configuring max-age*/
if (opts.days) {
opts['max-age'] = opts.days * 60 * 60 * 24;
/*Deleting days from options to pass remaining opts to cookie settings*/
delete opts.days
}
/*Configuring options to cookie standard by reducing each property*/
opts = Object.entries(opts).reduce(
(accumulatedStr, [k, v]) => `${accumulatedStr}; ${k}=${v}`, ''
)
/*Finally, creating the key*/
document.cookie = name + '=' + encodeURIComponent(value) + opts
},
delete: (name, opts) => Cookie.set(name, '', {'max-age': -1, ...opts})
// path & domain must match cookie being deleted
}
Cookie.set('user', 'Jim', {path: '/', days: 10})
// Set the path to top level (instead of page) and expiration to 10 days (instead of session)
Usage - Cookie.get(name, value [, options]):
options supports all standard cookie options and adds "days":
path: '/' - any absolute path. Default: current document location,
domain: 'sub.example.com' - may not start with dot. Default: current host without subdomain.
secure: true - Only serve cookie over https. Default: false.
days: 2 - days till cookie expires. Default: End of session.
Alternative ways of setting expiration:
expires: 'Sun, 18 Feb 2018 16:23:42 GMT' - date of expiry as a GMT string.
Current date can be gotten with: new Date(Date.now()).toUTCString()
'max-age': 30 - same as days, but in seconds instead of days.
Other answers use "expires" instead of "max-age" to support older IE versions. This method requires ES7, so IE7 is out anyways (this is not a big deal).
Note: Funny characters such as "=" and "{:}" are supported as cookie values, and the regex handles leading and trailing whitespace (from other libs).
If you would like to store objects, either encode them before and after with and JSON.stringify and JSON.parse, edit the above, or add another method. Eg:
Cookie.getJSON = name => JSON.parse(Cookie.get(name))
Cookie.setJSON = (name, value, opts) => Cookie.set(name, JSON.stringify(value), opts);

Mozilla created a simple framework for reading and writing cookies with full unicode support along with examples of how to use it.
Once included on the page, you can set a cookie:
docCookies.setItem(name, value);
read a cookie:
docCookies.getItem(name);
or delete a cookie:
docCookies.removeItem(name);
For example:
// sets a cookie called 'myCookie' with value 'Chocolate Chip'
docCookies.setItem('myCookie', 'Chocolate Chip');
// reads the value of a cookie called 'myCookie' and assigns to variable
var myCookie = docCookies.getItem('myCookie');
// removes the cookie called 'myCookie'
docCookies.removeItem('myCookie');
See more examples and details on Mozilla's document.cookie page.
A version of this simple js file is on github.

For those who need save objects like {foo: 'bar'}, I share my edited version of #KevinBurke's answer. I've added JSON.stringify and JSON.parse, that's all.
cookie = {
set: function (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 + "=" + JSON.stringify(value) + expires + "; path=/";
},
get : function(name){
var nameEQ = name + "=",
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 JSON.parse(c.substring(nameEQ.length,c.length));
}
return null;
}
}
So, now you can do things like this:
cookie.set('cookie_key', {foo: 'bar'}, 30);
cookie.get('cookie_key'); // {foo: 'bar'}
cookie.set('cookie_key', 'baz', 30);
cookie.get('cookie_key'); // 'baz'

I've used accepted answer of this thread many times already. It's great piece of code: Simple and usable. But I usually use babel and ES6 and modules, so if you are like me, here is code to copy for faster developing with ES6
Accepted answer rewritten as module with ES6:
export const createCookie = ({name, value, days}) => {
let expires;
if (days) {
let date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = '; expires=' + date.toUTCString();
} else {
expires = '';
}
document.cookie = name + '=' + value + expires + '; path=/';
};
export const getCookie = ({name}) => {
if (document.cookie.length > 0) {
let c_start = document.cookie.indexOf(name + '=');
if (c_start !== -1) {
c_start = c_start + name.length + 1;
let c_end = document.cookie.indexOf(';', c_start);
if (c_end === -1) {
c_end = document.cookie.length;
}
return unescape(document.cookie.substring(c_start, c_end));
}
}
return '';
};
And after this you can simply import it as any module (path of course may vary):
import {createCookie, getCookie} from './../helpers/Cookie';

Here's a code to Get, Set and Delete Cookie in JavaScript.
function getCookie(name) {
name = name + "=";
var cookies = document.cookie.split(';');
for(var i = 0; i <cookies.length; i++) {
var cookie = cookies[i];
while (cookie.charAt(0)==' ') {
cookie = cookie.substring(1);
}
if (cookie.indexOf(name) == 0) {
return cookie.substring(name.length,cookie.length);
}
}
return "";
}
function setCookie(name, value, expirydays) {
var d = new Date();
d.setTime(d.getTime() + (expirydays*24*60*60*1000));
var expires = "expires="+ d.toUTCString();
document.cookie = name + "=" + value + "; " + expires;
}
function deleteCookie(name){
setCookie(name,"",-1);
}
Source: http://mycodingtricks.com/snippets/javascript/javascript-cookies/

Performance benchmark
Comparison of ES6 versions of some popular getCookie functions (with my improvements):
https://www.measurethat.net/Benchmarks/Show/16012/5/getcookie-for-vs-forof-vs-indexof-vs-find-vs-reduce
TL;DR: for...of version seams to be fastest for real-life cookies data :)
Important: document.cookie can provide duplicated cookie names if there are cookies with the same name for path=/ and current page path (eg. path=/faq). But the cookie for the current path will always be the first in the string, so be aware of this when using the reduce() version from the other answer provided here (it returns the last found cookie instead of the first one).
Fixed reduce() version is further in my answer.
For..of version:
Fastest for the real-life benchmark data set (10 cookies with long values). But performance results are almost the same as with vanilla for loop and with Array.find(), so use which you like :)
function getCookieForOf(name) {
const nameEQ = name + '=';
for (const cookie of document.cookie.split('; ')) {
if (cookie.indexOf(nameEQ) === 0) {
const value = cookie.substring(nameEQ.length);
return decodeURIComponent(value); // returns first found cookie
}
}
return null;
}
IndexOf version
Incredibly fast in the artificial test set of 1000 cookies with short values (because it doesn't create an array with 1000 records). To be honest, I consider there could be a bug in the test code that makes this version so crazy fast (if you would find some, pls let me know). Anyway, it's rather not probable to have 1000 cookies in the real App ;)
It's slow for the real-world test data set with 10 long cookies.
function getCookieIndexOf(name) {
const nameEQ = name + '=';
const cookies = document.cookie;
const cookieStart = cookies.indexOf(nameEQ);
if (cookieStart !== -1) {
const cookieValueStart = cookieStart + nameEQ.length;
const cookieEnd = cookies.indexOf(';', cookieValueStart);
const value = cookies.substring(
cookieValueStart,
cookieEnd !== -1 ? cookieEnd : undefined
);
return decodeURIComponent(value); // returns first found cookie
}
return null;
}
Array.find() version
function getCookieFind(name) {
const nameEQ = name + '=';
const foundCookie = document.cookie
.split('; ')
.find(c => c.indexOf(nameEQ) === 0); // returns first found cookie
if (foundCookie) {
return decodeURIComponent(foundCookie.substring(nameEQ.length));
}
return null;
}
Vanilla, old-school, for-loop version ;)
function getCookieFor(name) {
const nameEQ = name + "=";
const ca = cookies.split('; ');
for(let i=0; i < ca.length; i++) {
const c = ca[i];
if (c.indexOf(nameEQ) === 0) {
const value = c.substring(nameEQ.length);
return decodeURIComponent(value); // returns first found cookie
}
}
return null;
}
// ES5 version:
function getCookieFor(name) {
var nameEQ = name + "=";
var ca = cookies.split('; ');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
if (c.indexOf(nameEQ) === 0) {
var value = c.substring(nameEQ.length);
return decodeURIComponent(value); // returns first found cookie
}
}
return null;
}
Array.reduce() version
My fixed version of this answer from #artnikpro - returns the first found cookie, so works better with duplicated cookie names for the current path (e.g. path=/faq) and path=/.
This version is the slowest one in all performance tests, so IMHO should be avoided.
function getCookieReduce(name) {
return document.cookie.split('; ').reduce((r, v) => {
const [n, ...val] = v.split('='); // cookie value can contain "="
if(r) return r; // returns first found cookie
return n === name ? decodeURIComponent(val.join('=')) : r; // returns last found cookie (overwrites)
}, '');
}
You can run benchmarks by yourself here: https://www.measurethat.net/Benchmarks/Show/16012/5/getcookie-for-vs-forof-vs-indexof-vs-find-vs-reduce
setCookie() TypeScript function
Here is also my version of the function to set a cookie with encodeURIComponent, TypeScript, and SameSite option (which will be required by Firefox soon):
function setCookie(
name: string,
value: string = '',
days: number | false = false, // session length if not provided
path: string = '/', // provide an empty string '' to set for current path (managed by a browser)
sameSite: 'none' | 'lax' | 'strict' = 'lax', // required by Firefox
isSecure?: boolean
) {
let expires = '';
if (days) {
const date = new Date(
Date.now() + days * 24 * 60 * 60 * 1000
).toUTCString();
expires = '; expires=' + date;
}
const secure = isSecure || sameSite === 'none' ? `; Secure` : '';
const encodedValue = encodeURIComponent(value);
document.cookie = `${name}=${encodedValue}${expires}; path=${path}; SameSite=${sameSite}${secure}`;
}
Google Chrome Cookie Storage API
Thanks to #oncode answer it's worth mentioning that the Google Chrome team has proposed some standardization (finally! It's really ridiculous that we still don't have any commonly accepted API for cookies) with asynchronous Cookie Storage API (available in Google Chrome starting from version 87): https://wicg.github.io/cookie-store/
Unfortunately, it's still unofficial and isn't even under W3C consideration nor ES proposal: github.com/tc39/proposals
Such a shame we still don't have any standard API for cookies...
Fortunately, we have cookie-store polyfill for other browsers as npm package (gitHub), which is only 1.7kB Gzipped ;)

I use this object. Values are encoded, so it's necessary to consider it when reading or writing from server side.
cookie = (function() {
/**
* Sets a cookie value. seconds parameter is optional
*/
var set = function(name, value, seconds) {
var expires = seconds ? '; expires=' + new Date(new Date().getTime() + seconds * 1000).toGMTString() : '';
document.cookie = name + '=' + encodeURIComponent(value) + expires + '; path=/';
};
var map = function() {
var map = {};
var kvs = document.cookie.split('; ');
for (var i = 0; i < kvs.length; i++) {
var kv = kvs[i].split('=');
map[kv[0]] = decodeURIComponent(kv[1]);
}
return map;
};
var get = function(name) {
return map()[name];
};
var remove = function(name) {
set(name, '', -1);
};
return {
set: set,
get: get,
remove: remove,
map: map
};
})();

For reading simple querystrings, this one-liner might work for you in recent versions of JavaScript:
let cookies = Object.fromEntries(document.cookie.split(';').map(i=>i.trim().split('=')));
And now you have a JavaScript Object with keys and values.
For creating, you can try this one:
let cookieObject = {foo: 'bar', ping: "pong"}
Object.entries(cookieObject).map((e)=>`${e[0]}=${e[1]}`).join(';')

I've used js-cookie to success.
<script src="/path/to/js.cookie.js"></script>
<script>
Cookies.set('foo', 'bar');
Cookies.get('foo');
</script>

You can use my cookie ES module for get/set/remove cookie.
Usage:
In your head tag, include the following code:
<script src="https://raw.githack.com/anhr/cookieNodeJS/master/build/cookie.js"></script>
or
<script src="https://raw.githack.com/anhr/cookieNodeJS/master/build/cookie.min.js"></script>
Now you can use window.cookie for store user information in web pages.
cookie.isEnabled()
Is the cookie enabled in your web browser?
returns {boolean} true if cookie enabled.
Example
if ( cookie.isEnabled() )
console.log('cookie is enabled on your browser');
else
console.error('cookie is disabled on your browser');
cookie.set( name, value )
Set a cookie.
name: cookie name.
value: cookie value.
Example
cookie.set('age', 25);
cookie.get( name[, defaultValue] );
get a cookie.
name: cookie name.
defaultValue: cookie default value. Default is undefined.
returns cookie value or defaultValue if cookie was not found
Example
var age = cookie.get('age', 25);
cookie.remove( name );
Remove cookie.
name: cookie name.
Example
cookie.remove( 'age' );
Example of usage

I use the following functions, which I have written by taking the best I have found from various sources and weeded out some bugs or discrepancies.
The function setCookie does not have advanced options, just the simple stuff, but the code is easy to understand, which is always a plus:
function setCookie(name, value, daysToLive = 3650) { // 10 years default
let cookie = name + "=" + encodeURIComponent(value);
if (typeof daysToLive === "number") {
cookie += "; max-age=" + (daysToLive * 24 * 60 * 60);
document.cookie = cookie + ";path=/";
}
}
function getCookie(name) {
let cookieArr = document.cookie.split(";");
for (let i = 0; i < cookieArr.length; i++) {
let cookiePair = cookieArr[i].split("=");
if (name == cookiePair[0].trim()) {
return decodeURIComponent(cookiePair[1].trim());
}
}
return undefined;
}
function deleteCookie(name) {
setCookie(name, '', -1);
}

The chrome team has proposed a new way of managing cookies asynchronous with the Cookie Storage API (available in Google Chrome starting from version 87): https://wicg.github.io/cookie-store/
Use it already today with a polyfill for the other browsers: https://github.com/mkay581/cookie-store
// load polyfill
import 'cookie-store';
// set a cookie
await cookieStore.set('name', 'value');
// get a cookie
const savedValue = await cookieStore.get('name');

Very short ES6 functions using template literals. Be aware that you need to encode/decode the values by yourself but it'll work out of the box for simplier purposes like storing version numbers.
const getCookie = (cookieName) => {
return (document.cookie.match(`(^|;) *${cookieName}=([^;]*)`)||[])[2]
}
const setCookie = (cookieName, value, days=360, path='/') => {
let expires = (new Date(Date.now()+ days*86400*1000)).toUTCString();
document.cookie = `${cookieName}=${value};expires=${expires};path=${path};`
}
const deleteCookie = (cookieName) => {
document.cookie = `${cookieName}=;expires=Thu, 01 Jan 1970 00:00:01 GMT;path=/;`;
}

Simple way to read cookies in ES6.
function getCookies() {
var cookies = {};
for (let cookie of document.cookie.split('; ')) {
let [name, value] = cookie.split("=");
cookies[name] = decodeURIComponent(value);
}
console.dir(cookies);
}

Through a interface similar to sessionStorage and localStorage:
const cookieStorage = {
getItem: (key) {
const cookies = document.cookie.split(';')
.map(cookie => cookie.split('='))
.reduce(
(accumulation, [key, value]) => ({...accumulation, [key.trim()]: value}),
{}
)
return cookies[key]
},
setItem: (key, value) {
document.cookie = `${key}=${value}`
},
}
Its usage cookieStorage.setItem('', '') and cookieStorage.getItem('').

An improved version of the readCookie:
function readCookie( name )
{
var cookieParts = document.cookie.split( ';' )
, i = 0
, part
, part_data
, value
;
while( part = cookieParts[ i++ ] )
{
part_data = part.split( '=' );
if ( part_data.shift().replace(/\s/, '' ) === name )
{
value = part_data.shift();
break;
}
}
return value;
}
This should break as soon as you have found your cookie value and return its value. In my opinion very elegant with the double split.
The replace on the if-condition is a white space trim, to make sure it matches correctly

I have written simple cookieUtils, it has three functions for creating the cookie, reading the cookie and deleting the cookie.
var CookieUtils = {
createCookie: function (name, value, expireTime) {
expireTime = !!expireTime ? expireTime : (15 * 60 * 1000); // Default 15 min
var date = new Date();
date.setTime(date.getTime() + expireTime);
var expires = "; expires=" + date.toGMTString();
document.cookie = name + "=" + value + expires + "; path=/";
},
getCookie: function (name) {
var value = "; " + document.cookie;
var parts = value.split("; " + name + "=");
if (parts.length == 2) {
return parts.pop().split(";").shift();
}
},
deleteCookie: function(name) {
document.cookie = name +'=; Path=/; Expires=Thu, 01 Jan 1970 00:00:01 GMT;';
}
};

Here is the example from w3chools that was mentioned.
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 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 "";
}

A simple read
var getCookie = function (name) {
var valueStart = document.cookie.indexOf(name + "=") + name.length + 1;
var valueEnd = document.cookie.indexOf(";", valueStart);
return document.cookie.slice(valueStart, valueEnd)
}

A cheeky and simple way of reading a cookie could be something like:
let username, id;
eval(document.cookie);
console.log(username + ", " + id); // John Doe, 123
This could be used if you know your cookie contains something like: username="John Doe"; id=123;. Note that a string would need quotes in the cookie. Not the recommended way probably, but works for testing/learning.

Related

Deleting all cookies with JavaScript [duplicate]

How do you delete all the cookies for the current domain using JavaScript?
function deleteAllCookies() {
const cookies = document.cookie.split(";");
for (let i = 0; i < cookies.length; i++) {
const cookie = cookies[i];
const eqPos = cookie.indexOf("=");
const name = eqPos > -1 ? cookie.substr(0, eqPos) : cookie;
document.cookie = name + "=;expires=Thu, 01 Jan 1970 00:00:00 GMT";
}
}
Note that this code has two limitations:
It will not delete cookies with HttpOnly flag set, as the HttpOnly flag disables Javascript's access to the cookie.
It will not delete cookies that have been set with a Path value. (This is despite the fact that those cookies will appear in document.cookie, but you can't delete it without specifying the same Path value with which it was set.)
One liner
In case you want to paste it in quickly...
document.cookie.split(";").forEach(function(c) { document.cookie = c.replace(/^ +/, "").replace(/=.*/, "=;expires=" + new Date().toUTCString() + ";path=/"); });
And the code for a bookmarklet :
javascript:(function(){document.cookie.split(";").forEach(function(c) { document.cookie = c.replace(/^ +/, "").replace(/=.*/, "=;expires=" + new Date().toUTCString() + ";path=/"); }); })();
And here's one to clear all cookies in all paths and all variants of the domain (www.mydomain.example, mydomain.example etc):
(function () {
var cookies = document.cookie.split("; ");
for (var c = 0; c < cookies.length; c++) {
var d = window.location.hostname.split(".");
while (d.length > 0) {
var cookieBase = encodeURIComponent(cookies[c].split(";")[0].split("=")[0]) + '=; expires=Thu, 01-Jan-1970 00:00:01 GMT; domain=' + d.join('.') + ' ;path=';
var p = location.pathname.split('/');
document.cookie = cookieBase + '/';
while (p.length > 0) {
document.cookie = cookieBase + p.join('/');
p.pop();
};
d.shift();
}
}
})();
After a bit of frustration with this myself I knocked together this function which will attempt to delete a named cookie from all paths. Just call this for each of your cookies and you should be closer to deleting every cookie then you were before.
function eraseCookieFromAllPaths(name) {
// This function will attempt to remove a cookie from all paths.
var pathBits = location.pathname.split('/');
var pathCurrent = ' path=';
// do a simple pathless delete first.
document.cookie = name + '=; expires=Thu, 01-Jan-1970 00:00:01 GMT;';
for (var i = 0; i < pathBits.length; i++) {
pathCurrent += ((pathCurrent.substr(-1) != '/') ? '/' : '') + pathBits[i];
document.cookie = name + '=; expires=Thu, 01-Jan-1970 00:00:01 GMT;' + pathCurrent + ';';
}
}
As always different browsers have different behaviour but this worked for me.
Enjoy.
The following code will remove all cookies within the current domain and all trailing subdomains (www.some.sub.domain.example, .some.sub.domain.example, .sub.domain.example and so on.).
A single line vanilla JS version (I think the only one here without the use of cookie.split()):
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}`)
);
If you have access to the jquery.cookie plugin, you can erase all cookies this way:
for (var it in $.cookie()) $.removeCookie(it);
An answer influenced by both second answer here and W3Schools
document.cookie.split(';').forEach(function(c) {
document.cookie = c.trim().split('=')[0] + '=;' + 'expires=Thu, 01 Jan 1970 00:00:00 UTC;';
});
Seems to be working
edit: wow almost exactly the same as Zach's interesting how Stack Overflow put them next to each other.
edit: nvm that was temporary apparently
If you are concerned about clearing cookies only on a secured origin you can use the Cookie Store API and it's .delete() method.
cookieStore.getAll().then(cookies => cookies.forEach(cookie => {
console.log('Cookie deleted:', cookie);
cookieStore.delete(cookie.name);
}));
Visit the caniuse.com table for the Cookie Store API to check for browser support.
As far as I know there's no way to do a blanket delete of any cookie set on the domain. You can clear a cookie if you know the name and if the script is on the same domain as the cookie.
You can set the value to empty and the expiration date to somewhere in the past:
var mydate = new Date();
mydate.setTime(mydate.getTime() - 1);
document.cookie = "username=; expires=" + mydate.toGMTString();
There's an excellent article here on manipulating cookies using javascript.
Simpler. Faster.
function deleteAllCookies() {
var c = document.cookie.split("; ");
for (i in c)
document.cookie =/^[^=]+/.exec(c[i])[0]+"=;expires=Thu, 01 Jan 1970 00:00:00 GMT";
}
I don't know why the first voted answer doesn't work for me.
As this answer said:
There is no 100% solution to delete browser cookies.
The problem is that cookies are uniquely identified by not just by their key "name" but also their "domain" and "path".
Without knowing the "domain" and "path" of a cookie, you cannot reliably delete it. This information is not available through JavaScript's document.cookie. It's not available through the HTTP Cookie header either!
So my idea is to add a Cookie version control with the full set of setting, getting, removing of cookies:
var cookie_version_control = '---2018/5/11';
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+cookie_version_control + "=" + (value || "") + expires + "; path=/";
}
function getCookie(name) {
var nameEQ = name+cookie_version_control + "=";
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 removeCookie(name) {
document.cookie = name+cookie_version_control+'=; Max-Age=-99999999;';
}
document.cookie.split(";").forEach(function(c) {
document.cookie = c.replace(/^ +/, "").replace(/=.*/, "=;expires=" + new Date().toUTCString() + ";path=/");
});
//clearing local storage
localStorage.clear();
Figured I'd share this method for clearing cookies. Perhaps it may be helpful for someone else at some point.
var cookie = document.cookie.split(';');
for (var i = 0; i < cookie.length; i++) {
var chip = cookie[i],
entry = chip.split("="),
name = entry[0];
document.cookie = name + '=; expires=Thu, 01 Jan 1970 00:00:01 GMT;';
}
I have some more sophisticated and OOP-oriented cookie control module. It also contains deleteAll method to clear all existing cookie. Make notice that this version of deleteAll method has setting path=/ that causes deleting of all cookies within current domain. If you need to delete cookies only from some scope you will have to upgrade this method my adding dynamic path parameter to this method.
There is main Cookie class:
import {Setter} from './Setter';
export class Cookie {
/**
* #param {string} key
* #return {string|undefined}
*/
static get(key) {
key = key.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g, '\\$1');
const regExp = new RegExp('(?:^|; )' + key + '=([^;]*)');
const matches = document.cookie.match(regExp);
return matches
? decodeURIComponent(matches[1])
: undefined;
}
/**
* #param {string} name
*/
static delete(name) {
this.set(name, '', { expires: -1 });
}
static deleteAll() {
const cookies = document.cookie.split('; ');
for (let cookie of cookies) {
const index = cookie.indexOf('=');
const name = ~index
? cookie.substr(0, index)
: cookie;
document.cookie = name + '=;expires=Thu, 01 Jan 1970 00:00:00 GMT;path=/';
}
}
/**
* #param {string} name
* #param {string|boolean} value
* #param {{expires?:Date|string|number,path?:string,domain?:string,secure?:boolean}} opts
*/
static set(name, value, opts = {}) {
Setter.set(name, value, opts);
}
}
Cookie setter method (Cookie.set) is rather complex so I decomposed it into other class. There is code of this one:
export class Setter {
/**
* #param {string} name
* #param {string|boolean} value
* #param {{expires?:Date|string|number,path?:string,domain?:string,secure?:boolean}} opts
*/
static set(name, value, opts = {}) {
value = Setter.prepareValue(value);
opts = Setter.prepareOpts(opts);
let updatedCookie = name + '=' + value;
for (let i in opts) {
if (!opts.hasOwnProperty(i)) continue;
updatedCookie += '; ' + i;
const value = opts[i];
if (value !== true)
updatedCookie += '=' + value;
}
document.cookie = updatedCookie;
}
/**
* #param {string} value
* #return {string}
* #private
*/
static prepareValue(value) {
return encodeURIComponent(value);
}
/**
* #param {{expires?:Date|string|number,path?:string,domain?:string,secure?:boolean}} opts
* #private
*/
static prepareOpts(opts = {}) {
opts = Object.assign({}, opts);
let {expires} = opts;
if (typeof expires == 'number' && expires) {
const date = new Date();
date.setTime(date.getTime() + expires * 1000);
expires = opts.expires = date;
}
if (expires && expires.toUTCString)
opts.expires = expires.toUTCString();
return opts;
}
}
Here's a simple code to delete all cookies in JavaScript.
function deleteAllCookies(){
var cookies = document.cookie.split(";");
for (var i = 0; i < cookies.length; i++)
deleteCookie(cookies[i].split("=")[0]);
}
function setCookie(name, value, expirydays) {
var d = new Date();
d.setTime(d.getTime() + (expirydays*24*60*60*1000));
var expires = "expires="+ d.toUTCString();
document.cookie = name + "=" + value + "; " + expires;
}
function deleteCookie(name){
setCookie(name,"",-1);
}
Run the function deleteAllCookies() to clear all cookies.
You can get a list by looking into the document.cookie variable. Clearing them all is just a matter of looping over all of them and clearing them one by one.
//Delete all cookies
function deleteAllCookies() {
var cookies = document.cookie.split(";");
for (var i = 0; i < cookies.length; i++) {
var cookie = cookies[i];
var eqPos = cookie.indexOf("=");
var name = eqPos > -1 ? cookie.substr(0, eqPos) : cookie;
document.cookie = name + '=;' +
'expires=Thu, 01-Jan-1970 00:00:01 GMT;' +
'path=' + '/;' +
'domain=' + window.location.host + ';' +
'secure=;';
}
}
Functional Approach + ES6
const cookieCleaner = () => {
return document.cookie.split(";").reduce(function (acc, cookie) {
const eqPos = cookie.indexOf("=");
const cleanCookie = `${cookie.substr(0, eqPos)}=;expires=Thu, 01 Jan 1970 00:00:00 GMT;`;
return `${acc}${cleanCookie}`;
}, "");
}
Note: Doesn't handle paths
Several answers here do not resolve the path question. I believe that: if you control the site, or part of it, you should know all the paths used. So you just have to have it delete all cookies from all paths used.
Because my site already has jquery (and out of laziness) I decided to use the jquery cookie, but you can easily adapt it to pure javascript based on the other answers.
In this example I remove three specific paths that were being used by the ecommerce platform.
let mainURL = getMainURL().toLowerCase().replace('www.', '').replace('.com.br', '.com'); // i am a brazilian guy
let cookies = $.cookie();
for(key in cookies){
// default remove
$.removeCookie(key, {
path:'/'
});
// remove without www
$.removeCookie(key, {
domain: mainURL,
path: '/'
});
// remove with www
$.removeCookie(key, {
domain: 'www.' + mainURL,
path: '/'
});
};
// get-main-url.js v1
function getMainURL(url = window.location.href){
url = url.replace(/.+?\/\//, ''); // remove protocol
url = url.replace(/(\#|\?|\/)(.+)?/, ''); // remove parameters and paths
// remove subdomain
if( url.split('.').length === 3 ){
url = url.split('.');
url.shift();
url = url.join('.');
};
return url;
};
I changed the .com site to .com.br because my site is multi domain and multi lingual
I'm contributing here because this function will allow you to delete all cookies (matching the path, by default no-path or \) also cookies that were set to be included on subdomains
function clearCookies( wildcardDomain=false, primaryDomain=true, path=null ){
pathSegment = path ? '; path=' + path : ''
expSegment = "=;expires=Thu, 01 Jan 1970 00:00:00 GMT"
document.cookie.split(';').forEach(
function(c) {
primaryDomain && (document.cookie = c.replace(/^ +/, "").replace(/=.*/, expSegment + pathSegment))
wildcardDomain && (document.cookie = c.replace(/^ +/, "").replace(/=.*/, expSegment + pathSegment + '; domain=' + document.domain))
}
)
}
This works for me:
function deleteCookie(name) {
document.cookie =
`${name}=; Expires=Thu, 01 Jan 1970 00:00:01 GMT; Path=/`;
// Remove it from local storage too
window.localStorage.removeItem(name);
}
function deleteAllCookies() {
const cookies = document.cookie.split("; ");
cookies.forEach((cookie) => {
const name = cookie.split("=").shift();
this.deleteCookie(name);
});
// Some sites backup cookies in `localStorage`
window.localStorage.clear();
}
After testing almost ever method listed in multiple style of browsers on multiple styles of cookies, I found almost nothing here works even 50%.
Please help correct as needed, but I'm going to throw my 2 cents in here. The following method breaks everything down and basically builds the cookie value string based on both the settings pieces as well as including a step by step build of the path string, starting with / of course.
Hope this helps others and I hope any criticism may come in the form of perfecting this method. At first I wanted a simple 1-liner as some others sought, but JS cookies are one of those things not so easily dealt with.
;(function() {
if (!window['deleteAllCookies'] && document['cookie']) {
window.deleteAllCookies = function(showLog) {
var arrCookies = document.cookie.split(';'),
arrPaths = location.pathname.replace(/^\//, '').split('/'), // remove leading '/' and split any existing paths
arrTemplate = [ 'expires=Thu, 01-Jan-1970 00:00:01 GMT', 'path={path}', 'domain=' + window.location.host, 'secure=' ]; // array of cookie settings in order tested and found most useful in establishing a "delete"
for (var i in arrCookies) {
var strCookie = arrCookies[i];
if (typeof strCookie == 'string' && strCookie.indexOf('=') >= 0) {
var strName = strCookie.split('=')[0]; // the cookie name
for (var j=1;j<=arrTemplate.length;j++) {
if (document.cookie.indexOf(strName) < 0) break; // if this is true, then the cookie no longer exist
else {
var strValue = strName + '=; ' + arrTemplate.slice(0, j).join('; ') + ';'; // made using the temp array of settings, putting it together piece by piece as loop rolls on
if (j == 1) document.cookie = strValue;
else {
for (var k=0;k<=arrPaths.length;k++) {
if (document.cookie.indexOf(strName) < 0) break; // if this is true, then the cookie no longer exist
else {
var strPath = arrPaths.slice(0, k).join('/') + '/'; // builds path line
strValue = strValue.replace('{path}', strPath);
document.cookie = strValue;
}
}
}
}
}
}
}
showLog && window['console'] && console.info && console.info("\n\tCookies Have Been Deleted!\n\tdocument.cookie = \"" + document.cookie + "\"\n");
return document.cookie;
}
}
})();
Jquery:
var cookies = $.cookie();
for(var cookie in cookies) {
$.removeCookie(cookie);
}
vanilla JS
function clearListCookies()
{
var cookies = document.cookie.split(";");
for (var i = 0; i < cookies.length; i++)
{
var spcook = cookies[i].split("=");
deleteCookie(spcook[0]);
}
function deleteCookie(cookiename)
{
var d = new Date();
d.setDate(d.getDate() - 1);
var expires = ";expires="+d;
var name=cookiename;
//alert(name);
var value="";
document.cookie = name + "=" + value + expires + "; path=/acc/html";
}
window.location = ""; // TO REFRESH THE PAGE
}
If you'd like to use js-cookie npm package and remove cookies by name:
import cookie from 'js-cookie'
export const removeAllCookiesByName = (cookieName: string) => {
const hostParts = location.host.split('.')
const domains = hostParts.reduce(
(acc: string[], current, index) => [
...acc,
hostParts.slice(index).join('.'),
],
[]
)
domains.forEach((domain) => cookie.remove(cookieName, { domain }))
}
We can do it like so:
deleteAllCookies=()=>
{
let c=document.cookie.split(';')
for(const k of c)
{
let s=k.split('=')
document.cookie=s[0].trim()+'=;expires=Fri, 20 Aug 2021 00:00:00 UTC'
}
}
Usage:
deleteAllCookies()
the expiration date was a random day prior to this answer; it can be any date before the current day
In JS you cannot read through cookies based on path
In JS you can only set or get cookies
I found a problem in IE and Edge. Webkit browsers (Chrome, safari) seem to be more forgiving. When setting cookies, always set the "path" to something, because the default will be the page that set the cookie. So if you try to expire it on a different page without specifying the "path", the path won't match and it won't expire. The document.cookie value doesn't show the path or expiration for a cookie, so you can't derive where the cookie was set by looking at the value.
If you need to expire cookies from different pages, save the path of the setting page in the cookie value so you can pull it out later or always append "; path=/;" to the cookie value. Then it will expire from any page.

JS Pick Random Quotes on Page Refresh

I'm making my website and I want it so that every time the user refreshes the page, a new random joke pops up instead of the previously picked one. This is the script I have right now:
function ShowJoke(){
var Joke=["Jokes", "go", "here"];
var Pick = Math.floor(Math.random() * (Joke.length));
document.write(Joke[Pick]);
}
I can only answer with the information you've given, so if something is wrong, please tell me so I can fix it.
So with what I'm taking from this question, you want to load a new joke on page load. "every time the page refreshes a new random quote shows instead of the last one"
Note: The below snippet might not work due to "allow-same-origin" flag and most likely will not work hosted locally unless you are using something like XAMPP.
The throwdown is to check to see if cookie exists, if it does, keep generating until a new joke is generated not equal to the cookie, set the new cookie, and display the joke.
// Array of Jokes
var Jokes = [
"I just got fired from my job at the keyboard factory. They told me I wasn't putting in enough shifts.",
"We'll we'll we'll...if it isn't autocorrect.",
"Q. Which type of vegetable tries to be cool, but is only partly successful at it?\n\nA. The radish.",
"The world tongue-twister champion just got arrested. I hear they're gonna give him a really tough sentence."
];
// function to check cookie (true if exists, false if not)
function checkCookie(){
var joke = getCookie();
if (joke != "") {
return true;
} else {
return false;
}
}
// set the cookie so can be referenced later
function setCookie(cvalue){
var cname = "joke";
var d = new Date();
d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
var expires = "expires="+d.toUTCString();
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}
// actually acquire the cookie and read it
function getCookie() {
var cname = "joke";
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 "";
}
function ShowJoke(){
let randomNum = ~~(Math.random() * Jokes.length); // pick a random number from 0 to length of jokes
if(checkCookie()){ // check if cookie exists
while(Jokes[randomNum] != getCookie()) randomNum = ~~(Math.random() * Jokes.length);
} // while cookie's joke != generated joke
document.getElementById('Joke').textContent = Jokes[randomNum]; // set content
setCookie(Jokes[randomNum]); // set cookie
}
window.onload = ShowJoke(); // run on window load
<p id="Joke"></p>
Your code looks fine. But, you have syntax errors. Also, you are not calling the finction
function ShowJoke()
{
var Joke = [
'Joke1',
'Joke2',
'Joke3',
'Joke4',
'Joke5',
'Joke6'
];
var Pick = Math.floor(Math.random() * (Joke.length));
document.write(Joke[Pick]);
}
document.addEventListener("load", ShowJoke());
You just need to fix the typos
function ShowJoke()
{
var Joke=[1, 2, 3, 4, 5, 6, 7];
var Pick = Math.floor(Math.random() * (Joke.length));
document.write(Joke[Pick]);
}
and to actually call the function
ShowJoke();
EDIT:
It turns out that the op does not want to repeat the same joke, therefore we could do something like this:
function ShowJoke()
{
var RawJoke=[1, 2, 3, 4, 5, 6, 7];
var ToldJokes = localStorage.getItem("jokes");
if (ToldJokes) {
ToldJokes = JSON.parse(ToldJokes);
} else {
ToldJokes = [];
}
var Joke = [];
for (var i = 0; i < RawJoke.length; i++)
if (ToldJokes.indexOf(RawJoke[i]) === -1)
Joke.push(RawJoke[i]);
if (Joke.length === 0) {
ToldJokes = [];
Joke = RawJoke;
}
var Pick = Math.floor(Math.random() * (Joke.length));
ToldJokes.push(Joke[Pick]);
localStorage.setItem("jokes", JSON.stringify(ToldJokes));
document.write(Joke[Pick]);
}

document.cookie prints long string value [duplicate]

I found two functions to get cookie data with Javascript, one on w3schools.com and one on quirksmode.org
I would like to know which one I should use?
For example I believe I read somewhere that there was a problem with some browsers splitting the ; semicolon?
w3schools:
function getCookie(c_name) {
if (document.cookie.length > 0) {
c_start = document.cookie.indexOf(c_name + "=");
if (c_start != -1) {
c_start = c_start + c_name.length + 1;
c_end = document.cookie.indexOf(";", c_start);
if (c_end == -1) c_end = document.cookie.length;
return unescape(document.cookie.substring(c_start, c_end));
}
}
return "";
}
quirksmode:
function readCokie(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;
}
The function from W3CSchool is wrong. It fails if there are multiple cookies that have the same suffix like:
ffoo=bar; foo=baz
When you search for foo it will return the value of ffoo instead of foo.
Now here is what I would do: First of all, you need get to know the syntax of how cookies are transported. Netscape’s original specification (there are only copies available like this one at haxx.se) uses semicolons to separate multiple cookies while each name/value pair has the following syntax:
NAME=VALUE
This string is a sequence of characters excluding semi-colon, comma and white space. If there is a need to place such data in the name or value, some encoding method such as URL style %XX encoding is recommended, though no encoding is defined or required.
So splitting document.cookie string at semi-colons or commas is a viable option.
Besides that, RFC 2109 does also specify that cookies are separated by either semi-colons or commas:
cookie = "Cookie:" cookie-version
1*((";" | ",") cookie-value)
cookie-value = NAME "=" VALUE [";" path] [";" domain]
cookie-version = "$Version" "=" value
NAME = attr
VALUE = value
path = "$Path" "=" value
domain = "$Domain" "=" value
Although both are allowed, commas are preferred as they are the default separator of list items in HTTP.
Note: For backward compatibility, the separator in the Cookie header
is semi-colon (;) everywhere. A server should also accept comma (,)
as the separator between cookie-values for future compatibility.
Furthermore, the name/value pair has some further restrictions as the VALUE can also be a quoted string as specified in RFC 2616:
attr = token
value = token | quoted-string
So these two cookie versions need to be treated separately:
if (typeof String.prototype.trimLeft !== "function") {
String.prototype.trimLeft = function() {
return this.replace(/^\s+/, "");
};
}
if (typeof String.prototype.trimRight !== "function") {
String.prototype.trimRight = function() {
return this.replace(/\s+$/, "");
};
}
if (typeof Array.prototype.map !== "function") {
Array.prototype.map = function(callback, thisArg) {
for (var i=0, n=this.length, a=[]; i<n; i++) {
if (i in this) a[i] = callback.call(thisArg, this[i]);
}
return a;
};
}
function getCookies() {
var c = document.cookie, v = 0, cookies = {};
if (document.cookie.match(/^\s*\$Version=(?:"1"|1);\s*(.*)/)) {
c = RegExp.$1;
v = 1;
}
if (v === 0) {
c.split(/[,;]/).map(function(cookie) {
var parts = cookie.split(/=/, 2),
name = decodeURIComponent(parts[0].trimLeft()),
value = parts.length > 1 ? decodeURIComponent(parts[1].trimRight()) : null;
cookies[name] = value;
});
} else {
c.match(/(?:^|\s+)([!#$%&'*+\-.0-9A-Z^`a-z|~]+)=([!#$%&'*+\-.0-9A-Z^`a-z|~]*|"(?:[\x20-\x7E\x80\xFF]|\\[\x00-\x7F])*")(?=\s*[,;]|$)/g).map(function($0, $1) {
var name = $0,
value = $1.charAt(0) === '"'
? $1.substr(1, -1).replace(/\\(.)/g, "$1")
: $1;
cookies[name] = value;
});
}
return cookies;
}
function getCookie(name) {
return getCookies()[name];
}
Yes, the W3Schools solution is incorrect.
For those that would like it, here is a simpler solution that works. It just prepends a space so the single call to indexOf() only returns the correct cookie.
function getCookie(c_name) {
var c_value = " " + document.cookie;
var c_start = c_value.indexOf(" " + c_name + "=");
if (c_start == -1) {
c_value = null;
}
else {
c_start = c_value.indexOf("=", c_start) + 1;
var c_end = c_value.indexOf(";", c_start);
if (c_end == -1) {
c_end = c_value.length;
}
c_value = unescape(c_value.substring(c_start,c_end));
}
return c_value;
}
This, from w3schools, is incorrect in that it may lead to getting the wrong cookie:
c_start = document.cookie.indexOf(c_name + "=");
If you go looking for a cookie named foo (which we'll suppose is an existing cookie) then somewhere in document.cookie will be the string foo=bar.
However, there's no guarantee there won't also be the string xfoo=something. Notice that this still contains the substring foo= so the w3schools code will find it. And if the xfoo cookie happens to be listed first, you'll get back the something value (incorrectly!) instead of the expected bar.
Given the choice between two pieces of code, never go with the one that's fundamentally broken.
All of the code shown above is BROKEN. The two common problems are (1) the getcookie function may return the wrong value if one cookie name is a proper suffix of another cookie name; and (2) the setcookie function does not protect the cookie value, which means that if the cookie value includes (for example) a ";" then all the cookies are corrupted and cannot be parsed.
TL;DR Use this well-written library instead:
https://github.com/js-cookie/js-cookie
Here is my version, it covers the edge case of quoted values.
function getCookies() {
const REGEXP = /([\w\.]+)\s*=\s*(?:"((?:\\"|[^"])*)"|(.*?))\s*(?:[;,]|$)/g;
let cookies = {};
let match;
while( (match = REGEXP.exec(document.cookie)) !== null ) {
let value = match[2] || match[3];
cookies[match[1]] = decodeURIComponent(value);
}
return cookies;
}

New value for cookie appended

This javascript code
function writeCookie(CookieName, CookieValue, CookieDuration) {
var expiration = new Date();
var now = new Date();
expiration.setTime(now.getTime() + (parseInt(CookieDuration) * 60000));
document.cookie = CookieName + '=' + escape(CookieValue) + '; expires=' + expiration.toGMTString() +
'; path=/';
}
function readCookie(CookieName) {
if (document.cookie.length > 0) {
var beginning = document.cookie.indexOf(CookieName + "=");
if (beginning != -1) {
beginning = beginning + CookieName.length + 1;
var ending = document.cookie.indexOf(";", beginning);
if (ending == -1) ending = document.cookie.length;
return unescape(document.cookie.substring(beginning, ending));
}
else {
return "";
}
}
return "";
}
var before = readCookie('totali');
var after = before + 1;
writeCookie('totali', after, 43200);
Should read cookie 'totali', add "1" to its value and then rewrite the new value.
The first time I run the code, cookie becomes "1", but the second time becomes "11", the third "111" and so on.
What could be the problem?
You are concatenating strings. Convert the value read from the cookie into a number before attempting to add it:
var after = parseInt(before) + 1;
But the problem is that the first time you read the cookie, the value is an empty string, and parseInt("") will be NaN. In this case, you have to check before you use it. This will assign 1 if the function returns an empty string, or the value stored in the cookie + 1 if not:
var after = (before.trim() == "") ? 1 : parseInt(before) + 1;
This assumes you never place anything other than a number in that totali cookie.
See http://jsfiddle.net/9rLZP/3/ (I changed the name of the cookie, so you can see the change without having to remove the previous cookie)

How do I pass in a cookie value returned from a javascript function to a JSON parameter field?

I have this kendo object and I'm concerned with this part of its configuration:
data: {
awardTitleId: e.data.AwardTitleId,
personId: X, //needs to be a variable
nameId: Y //needs to be a variable
}
I get the values for personId and nameId and store them into 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 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) {
createCookie(name, "", -1);
}
The issue here is that for me to use the returned value from the "readCookie" function, it needs to be in a variable so I can do:
data: {
awardTitleId: e.data.AwardTitleId,
personId: variable1,
nameId: variable2
}
I can't do this:
data: {
awardTitleId: e.data.AwardTitleId,
personId: readCookie("personId"),
nameId: readCookie("nameId")
}
So my question is, how do I USE the values returned by these java script functions in my code? They sort of have to be "global variables" so that I can use it in other parts/events of the web page.
I tried declaring these variables at the top of my page, outside all functions but I keep getting 0's for the Ids.
The cookie functions ARE working, btw.
EDIT -
The function IS returning a value:
It looks like you're using jQuery so if you have a ready function you could set these values into your data object like this
var data: {
awardTitleId: e.data.AwardTitleId, //wherever you get this from
personId: null,
nameId: null
}
$(function(){
data.personId = readCookie("personId");
data.nameId = readCookie("nameId");
});
I'm not sure where your data object exactly lives, hopefully not at the global scope but you mention needing that globally earlier so that's where I've left it.
By assigning the personId and nameId in the ready function of the page then you will have them for the life of the page and won't need to continually get them from a cookie.

Categories

Resources