get variables cookies (javascript) - javascript

How can i use the variable "food" saved in the cookie.
Its because all my variables are deleted when i refresh my webpage and i must save them for use the after.
function guardar() {
name= "materiales";
value = food;
caduca = "31 Dec 2020 23:59:59 GMT";
document.cookie = name+"="+value+";expire= "+caduca;
}
function ReadCookie(){
alert(document.cookie);
}

function getCookie(cname)
{
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i = 0; i < ca.length; ++i)
{
var c = ca[i].trim();
if (c.indexOf(name) == 0)
return c.substring(name.length,c.length);
}
return "";
}
Function explained:
Take the cookiename as parameter (cname).
Create a variable (name) with the text to search for (cname + "=").
Split document.cookie on semicolons into an array called ca (ca = document.cookie.split(';')).
Loop through the ca array (i=0; i < ca.length; ++i), and read out each value trimmed (c = ca[i].trim()).
If the cookie is found (c.indexOf(name) == 0), return the value of the cookie (c.substring(name.length,c.length).
If the cookie is not found, return "".
see : http://www.w3schools.com/js/js_cookies.asp

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.

counter need persist to remember the last number

I found this fiddle:
https://jsfiddle.net/DinoMyte/sac63azn/3/
https://fiddle.jshell.net/DinoMyte/sac63azn/3/show/
var num = 10000000;
setInterval(function()
{
num++;
console.log(num);
$('div').text(num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","));
},6000);
and it works almost the way I want it to. It is a counter where every 6 seconds, it will add a 1 to the number. For example: the number starts at 10,000,000 and then every 6 seconds, it adds a 1 to the number. The problem is when a user refresh or reloads the page, the number reverts back to the original 10,000,000. If after refresh or reload, is it possible the number will be saved from the last time? Persist? For example: the number is now 10,000,008, 6 seconds later it is 10,000,009, then the user click away or refresh or reloads the page, it should remember where the last number was left off: 10,000,009 and start counting from there.
You can use localStorage for this.
Just use this code
var num = localStorage.getItem('evaluatedTimer') || 10000000;
setInterval(function()
{
num++;
console.log(num);
var currentTimer = num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
localStorage.setItem('evaluatedTimer', currentTimer');
$('div').text(currentTimer );
},6000);
You can set the var num value to javascript cookie. You can use the below javascript code to create, read or delete cookie val
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 eraseCookie(name) {
createCookie(name,"",-1);
}
So, in your case you can persist num value like this
var num = 10000000;
setInterval(function()
{
num++;
createCookie('persist_num', num, 1);
console.log(readCookie('persist_num'));
$('div').text(num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","));
},600);

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;
}

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.

javascript cookie, little help please

I am displaying a div on my site, and I want to only display this div 5 times that the user has visited my site. So after 5 times, it wont show the div anymore.
I can do it with cookies. But Im only familiar with PHP. Javascript isn't my strong side.
Does anybody have a short piece of code to set a cookie, increase it for every visit, and if value is greater than 5 then don't show the DIV anymore?
Thanks
let's say you have the variable visits in the cookies, you mainly use something similar to this
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 "";
}
var visits = getCookie("visits_number");
if (visists > 5)
document.getElementById("your_div_name").setAttribute("style", "visibility: hidde");
Quirksmode has an article discussing cookies, which also includes three very handy helper functions (scroll down to the bottom). Read the article and all will become clear anyway.
Just remember that all information is stored as a string, and hence it is retrieved as a string. Therefore you should definitely be doing some manual type juggling before performing any operations on the data. See here:
var x = 1;
createCookie("myVar", x);
var newX = readCookie("myVar") + 1;
alert(newX); // "11"
// --- instead, do this: ---
var newX = parseInt(readCookie("myVar"), 10) + 1;
Nobody will have exactly the piece of code you are asking for, but it should be easy to compose it yourself, starting from these 2 necessary functions:
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;
}

Categories

Resources