I'm having problem of creating a cookie, I have this code:
window.onload = function() {
var value = readCookie('username');
if(value == null){
alert("null");
document.cookie = "username=Bob; expires=Thu, 18 Dec 2016 12:00:00 UTC";
}
else
alert(value);
}
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;
}
When the page load I check if the cookie exists, if it doesn't, I pop up an alert saying that is null, then I create the cookie, but every time I load the page it always says its null. Now the problem is in the creation of the cookie or in the readCookie function. I can't find why this doesn't work.
UPDATE
So in google Chrome it won't work, but in internet explorer works perfectly, someone knows why? I would like to work in all browsers.
When I create an HTML page using that code and run it in a normal test environment, the problem you describe does not occur. It alerts null on the first load and Bob on the second load.
If, however, I tell the browser to load the page from file:///Users/david/tmp/jgfklgjkl/index.html instead of my test server at http://localhost:7007/, then it always alerts null.
Cookies are associated with a hostname, and you have to load the page over HTTP in order to use them.
You are presumably loading them from a local file, and that is where the problem lies, not with your code.
Try this function for reading cookie. I've been using it for quite too long and it's working fine so far
function getCookieValue(cookie_name) {
var cookie, cookies = document.cookie.split(';');
for (var i = cookies.length - 1; i >= 0; --i) {
cookie = cookies[i].split('=');
if (cookie[0].trim() === cookie_name)
return cookie[1];
}
return "";
}
Also if you are interested you could use this function for adding cookies for 10 years.
function addCookie(name, value) {
var expire = new Date();
expire.setFullYear(expire.getFullYear() + 10);
d.cookie = name + "=" + value + "; expires=" + expire.toGMTString() + "; path=/";
}
I've made a cookie using asp.net C# code and I want to retrieve its value in javascript
Here's my C# code:
HttpCookie cookie = new HttpCookie("doc1count");
cookie.Value = "hellonitesh";
I am using this code:
var cookie = '#HttpContext.Current.Request.Cookies["doc1count"].Value';
alert(cookie);
but its giving me garbage value.
Try to separate client and server side
Add cookies to responce on server:
HttpCookie myCookie= new HttpCookie("doc1count");
myCookie.Value = "hellonitesh";
HttpContext.Response.Cookies.Add(myCookie);
And retrieve it in javascript (You can find more examples
here)
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 "";
}
var myCookie = getCookie("doc1count")
Try to use jquery.cookie plugin to manage cookie at client end. Apart from this, I can see in your C# code you are not posting the cookie variable. So you should do like following -
HttpContext.Current.Response.Cookies.Add(new HttpCookie("cookie_name","cookie_value"));
You can probably just access it through ASP.NET variable by adding in the inline code I have right here. That's if you wanna be fairly simple about it, you can check if it contains anything with an if statement before assigning it I believe.
var cookie = '<%= Request.Cookies["cookieID"].ToString() %>';
alert(cookie);
Try this
var cookie = '#Request.Cookies["culture"].Value';
I have a blog that requires users to signup via email in order to view the full post. I want to skip this requirement if a user has already signed up.
Here's how it works.
User visits page, if cookie is presen then show content
If cookie is not present, user must signup
User signs up, cookie created.
The problem with my code is that it's post specific. e.g. Let's say we have Post A & Post B. If user opts in Post A, they will need to opt in again on Post B which is not good.
If they opt in on Post A, I want to recognize the cookie on Post B as well.
How can I adjust my code?
if (document.cookie.indexOf("entered_email")>=0) {
jQuery('.hidden-blog').slideDown();
}
$('.snp-subscribeform').on('submit', function() {
$('.hidden-blog').slideDown();
document.cookie="entered_email=true;expire=06/12/2018";
});
You need to set the path on the cookie to "/" which then allows any page on that site to see the cookie. When you do not set a path for the cookie value, it defaults to the path of the current page which restricts the visibility of that cookie to that path only.
Here are some utility functions for dealing with cookies that allow you to set the path or will default the path to "/".
Using these, your code would look like this:
if (readCookie("entered_email") === "1") {
jQuery('.hidden-blog').slideDown();
}
$('.snp-subscribeform').on('submit', function() {
$('.hidden-blog').slideDown();
// cookie path in this function defaults to "/" so all pages on the
// site can access the cookie
createCookie("entered_email", "1", 365 * 3);
});
And, here's the utility cookie management functions:
// createCookie()
// name and value are strings
// days is the number of days until cookie expiration
// path is optional and should start with a leading "/"
// and can limit which pages on your site can
// read the cookie.
// By default, all pages on the site can read
// the cookie if path is not specified
function createCookie(name, value, days, path) {
var date, expires = "";
path = path || "/";
if (days) {
date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
expires = "; expires=" + date.toGMTString();
}
document.cookie = name + "=" + value + expires + "; path=" + 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);
}
I am developing an application using jQuery that uses cookies. Right now, it is located at application.html on my PC desktop.
However, I cannot store and retrieve a cookie. I had included jquery-1.7.1.min.js, json2.js, and jquery.cookie.js in my HTML file in that order.
Here is how I am storing a cookie to last for 7 days:
$.cookie("people", JSON.stringify(people_obj_array), {expires: 7});
The global array people_obj_array looks like
[
{
"name": "Adam",
"age": 1,
},
{
"name": "Bob",
"age": 2,
},
{
"name": "Cathy",
"age": 3,
},
]
When I test JSON encryption with alert(JSON.stringify(people_obj_array)), it looks fine:
However, when I retrieve this cookie via:
alert($.cookie("people"));
before even refreshing the page, an alert pops up that reads "null." Shouldn't the text be the alert JSON string? Am I using the JQuery cookies library correctly?
Just to clarify, here is how I am testing:
$.cookie("people", JSON.stringify(people_obj_array), {expires: 7}); // store
alert($.cookie("people")); // attempt to retrieve
I have Firebug, and I am willing to do some Console tests.
It's probably the fact the file is on your desktop that's causing the problem. Browsers normally behave by serving up cookies based on the domain they were received from and their path.
You may not be able to read the cookie immediately after setting it: Writing a cookie involves setting headers in a HTTP request and, likewise, reading them involves reading headers in a HTTP response.
Try hosting your page on a web-server and see if that works for you.
If you are having troubles with the cookies plugin why not just make up your own cookie functions? Read, Write and (optional) delete.
var createCookie = 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 + '=' + value + expires + '; path=/';
};
var readCookie = 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;
};
var eraseCookie = function(name) {
createCookie(name, '', -1);
};
I cannot comment on the specific plugin as I have never used it.. however these functions all work and have been tested.
So for your example:
createCookie("people", JSON.stringify(people_obj_array), 7); // store
alert(readCookie("people")); // retrieve
eraseCookie("people"); // remove
alert(readCookie("people")); // oo look i'm no longer here.
From my research jquery.cookie.js is fairly old, and doesn't seem to be maintained any longer. You might have better luck using this library instead. Its description on Google Code is "Javascript Cookie Library with jQuery bindings and JSON support", and includes methods for everything you're trying to do!
What is the shortest, accurate, and cross-browser compatible method for reading a cookie in JavaScript?
Very often, while building stand-alone scripts (where I can't have any outside dependencies), I find myself adding a function for reading cookies, and usually fall-back on the QuirksMode.org readCookie() method (280 bytes, 216 minified.)
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;
}
It does the job, but its ugly, and adds quite a bit of bloat each time.
The method that jQuery.cookie uses something like this (modified, 165 bytes, 125 minified):
function read_cookie(key)
{
var result;
return (result = new RegExp('(?:^|; )' + encodeURIComponent(key) + '=([^;]*)').exec(document.cookie)) ? (result[1]) : null;
}
Note this is not a 'Code Golf' competition: I'm legitimately interested in reducing the size of my readCookie function, and in ensuring the solution I have is valid.
Shorter, more reliable and more performant than the current best-voted answer:
const getCookieValue = (name) => (
document.cookie.match('(^|;)\\s*' + name + '\\s*=\\s*([^;]+)')?.pop() || ''
)
A performance comparison of various approaches is shown here:
https://jsben.ch/AhMN6
Some notes on approach:
The regex approach is not only the fastest in most browsers, it yields the shortest function as well. Additionally it should be pointed out that according to the official spec (RFC 2109), the space after the semicolon which separates cookies in the document.cookie is optional and an argument could be made that it should not be relied upon. Additionally, whitespace is allowed before and after the equals sign (=) and an argument could be made that this potential whitespace should be factored into any reliable document.cookie parser. The regex above accounts for both of the above whitespace conditions.
This will only ever hit document.cookie ONE time. Every subsequent request will be instant.
(function(){
var cookies;
function readCookie(name,c,C,i){
if(cookies){ return cookies[name]; }
c = document.cookie.split('; ');
cookies = {};
for(i=c.length-1; i>=0; i--){
C = c[i].split('=');
cookies[C[0]] = C[1];
}
return cookies[name];
}
window.readCookie = readCookie; // or expose it however you want
})();
I'm afraid there really isn't a faster way than this general logic unless you're free to use .forEach which is browser dependent (even then you're not saving that much)
Your own example slightly compressed to 120 bytes:
function read_cookie(k,r){return(r=RegExp('(^|; )'+encodeURIComponent(k)+'=([^;]*)').exec(document.cookie))?r[2]:null;}
You can get it to 110 bytes if you make it a 1-letter function name, 90 bytes if you drop the encodeURIComponent.
I've gotten it down to 73 bytes, but to be fair it's 82 bytes when named readCookie and 102 bytes when then adding encodeURIComponent:
function C(k){return(document.cookie.match('(^|; )'+k+'=([^;]*)')||0)[2]}
Assumptions
Based on the question, I believe some assumptions / requirements for this function include:
It will be used as a library function, and so meant to be dropped into any codebase;
As such, it will need to work in many different environments, i.e. work with legacy JS code, CMSes of various levels of quality, etc.;
To inter-operate with code written by other people and/or code that you do not control, the function should not make any assumptions on how cookie names or values are encoded. Calling the function with a string "foo:bar[0]" should return a cookie (literally) named "foo:bar[0]";
New cookies may be written and/or existing cookies modified at any point during lifetime of the page.
Under these assumptions, it's clear that encodeURIComponent / decodeURIComponent should not be used; doing so assumes that the code that set the cookie also encoded it using these functions.
The regular expression approach gets problematic if the cookie name can contain special characters. jQuery.cookie works around this issue by encoding the cookie name (actually both name and value) when storing a cookie, and decoding the name when retrieving a cookie. A regular expression solution is below.
Unless you're only reading cookies you control completely, it would also be advisable to read cookies from document.cookie directly and not cache the results, since there is no way to know if the cache is invalid without reading document.cookie again.
(While accessing and parsing document.cookies will be slightly slower than using a cache, it would not be as slow as reading other parts of the DOM, since cookies do not play a role in the DOM / render trees.)
Loop-based function
Here goes the Code Golf answer, based on PPK's (loop-based) function:
function readCookie(name) {
name += '=';
for (var ca = document.cookie.split(/;\s*/), i = ca.length - 1; i >= 0; i--)
if (!ca[i].indexOf(name))
return ca[i].replace(name, '');
}
which when minified, comes to 128 characters (not counting the function name):
function readCookie(n){n+='=';for(var a=document.cookie.split(/;\s*/),i=a.length-1;i>=0;i--)if(!a[i].indexOf(n))return a[i].replace(n,'');}
Regular expression-based function
Update: If you really want a regular expression solution:
function readCookie(name) {
return (name = new RegExp('(?:^|;\\s*)' + ('' + name).replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&') + '=([^;]*)').exec(document.cookie)) && name[1];
}
This escapes any special characters in the cookie name before constructing the RegExp object. Minified, this comes to 134 characters (not counting the function name):
function readCookie(n){return(n=new RegExp('(?:^|;\\s*)'+(''+n).replace(/[-[\]{}()*+?.,\\^$|#\s]/g,'\\$&')+'=([^;]*)').exec(document.cookie))&&n[1];}
As Rudu and cwolves have pointed out in the comments, the regular-expression-escaping regex can be shortened by a few characters. I think it would be good to keep the escaping regex consistent (you may be using it elsewhere), but their suggestions are worth considering.
Notes
Both of these functions won't handle null or undefined, i.e. if there is a cookie named "null", readCookie(null) will return its value. If you need to handle this case, adapt the code accordingly.
code from google analytics ga.js
function c(a){
var d=[],
e=document.cookie.split(";");
a=RegExp("^\\s*"+a+"=\\s*(.*?)\\s*$");
for(var b=0;b<e.length;b++){
var f=e[b].match(a);
f&&d.push(f[1])
}
return d
}
How about this one?
function getCookie(k){var v=document.cookie.match('(^|;) ?'+k+'=([^;]*)(;|$)');return v?v[2]:null}
Counted 89 bytes without the function name.
The following function will allow differentiating between empty strings and undefined cookies. Undefined cookies will correctly return undefined and not an empty string unlike some of the other answers here.
function getCookie(name) {
return (document.cookie.match('(^|;) *'+name+'=([^;]*)')||[])[2];
}
The above worked fine for me on all browsers I checked, but as mentioned by #vanovm in comments, as per the specification the key/value may be surrounded by whitespace. Hence the following is more standard compliant.
function getCookie(name) {
return (document.cookie.match('(?:^|;)\\s*'+name.trim()+'\\s*=\\s*([^;]*?)\\s*(?:;|$)')||[])[1];
}
this in an object that you can read, write, overWrite and delete cookies.
var cookie = {
write : function (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;
},
read : function (name) {
if (document.cookie.indexOf(name) > -1) {
return document.cookie.split(name)[1].split("; ")[0].substr(1)
} else {
return "";
}
},
delete : function (cname) {
var d = new Date();
d.setTime(d.getTime() - 1000);
var expires = "expires="+d.toUTCString();
document.cookie = cname + "=; " + expires;
}
};
Here goes.. Cheers!
function getCookie(n) {
let a = `; ${document.cookie}`.match(`;\\s*${n}=([^;]+)`);
return a ? a[1] : '';
}
Note that I made use of ES6's template strings to compose the regex expression.
It's 2022, everything except Internet Explorer supports the URLSearchParams API (^1) and String.prototype.replaceAll API (^2), so we can horribly (ab)use them:
const cookies = new URLSearchParams(document.cookie.replaceAll('&', '%26').replaceAll('; ', '&'));
cookies.get('cookie name'); // returns undefined if not set, string otherwise
Both of these functions look equally valid in terms of reading cookie. You can shave a few bytes off though (and it really is getting into Code Golf territory here):
function readCookie(name) {
var nameEQ = name + "=", ca = document.cookie.split(';'), i = 0, c;
for(;i < ca.length;i++) {
c = ca[i];
while (c[0]==' ') c = c.substring(1);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length);
}
return null;
}
All I did with this is collapse all the variable declarations into one var statement, removed the unnecessary second arguments in calls to substring, and replace the one charAt call into an array dereference.
This still isn't as short as the second function you provided, but even that can have a few bytes taken off:
function read_cookie(key)
{
var result;
return (result = new RegExp('(^|; )' + encodeURIComponent(key) + '=([^;]*)').exec(document.cookie)) ? result[2] : null;
}
I changed the first sub-expression in the regular expression to be a capturing sub-expression, and changed the result[1] part to result[2] to coincide with this change; also removed the unnecessary parens around result[2].
To truly remove as much bloat as possible, consider not using a wrapper function at all:
try {
var myCookie = document.cookie.match('(^|;) *myCookie=([^;]*)')[2]
} catch (_) {
// handle missing cookie
}
As long as you're familiar with RegEx, that code is reasonably clean and easy to read.
To have all cookies accessible by name in a Map:
const cookies = "a=b ; c = d ;e=";
const map = cookies.split(";").map((s) => s.split("=").map((s) => s.trim())).reduce((m, [k, v]) => (m.set(k, v), m), new Map());
console.log(map); //Map(3) {'a' => 'b', 'c' => 'd', 'e' => ''}
map.get("a"); //returns "b"
map.get("c"); //returns "d"
map.get("e"); //returns ""
(edit: posted the wrong version first.. and a non-functional one at that. Updated to current, which uses an unparam function that is much like the second example.)
Nice idea in the first example cwolves. I built on both for a fairly compact cookie reading/writing function that works across multiple subdomains. Figured I'd share in case anyone else runs across this thread looking for that.
(function(s){
s.strToObj = function (x,splitter) {
for ( var y = {},p,a = x.split (splitter),L = a.length;L;) {
p = a[ --L].split ('=');
y[p[0]] = p[1]
}
return y
};
s.rwCookie = function (n,v,e) {
var d=document,
c= s.cookies||s.strToObj(d.cookie,'; '),
h=location.hostname,
domain;
if(v){
domain = h.slice(h.lastIndexOf('.',(h.lastIndexOf('.')-1))+1);
d.cookie = n + '=' + (c[n]=v) + (e ? '; expires=' + e : '') + '; domain=.' + domain + '; path=/'
}
return c[n]||c
};
})(some_global_namespace)
If you pass rwCookie nothing, it will get
all cookies into cookie storage
Passed rwCookie a cookie name, it gets that
cookie's value from storage
Passed a cookie value, it writes the cookie and places the value in storage
Expiration defaults to session unless you specify one
Using cwolves' answer, but not using a closure nor a pre-computed hash :
// Golfed it a bit, too...
function readCookie(n){
var c = document.cookie.split('; '),
i = c.length,
C;
for(; i>0; i--){
C = c[i].split('=');
if(C[0] == n) return C[1];
}
}
...and minifying...
function readCookie(n){var c=document.cookie.split('; '),i=c.length,C;for(;i>0;i--){C=c[i].split('=');if(C[0]==n)return C[1];}}
...equals 127 bytes.
Here is the simplest solution using javascript string functions.
document.cookie.substring(document.cookie.indexOf("COOKIE_NAME"),
document.cookie.indexOf(";",
document.cookie.indexOf("COOKIE_NAME"))).
substr(COOKIE_NAME.length);
Just to throw my hat in the race, here's my proposal:
function getCookie(name) {
const cookieDict = document.cookie.split(';')
.map((x)=>x.split('='))
.reduce((accum,current) => { accum[current[0]]=current[1]; return accum;}, Object());
return cookieDict[name];
}
The above code generates a dict that stores cookies as key-value pairs (i.e., cookieDict), and afterwards accesses the property name to retrieve the cookie.
This could effectively be expressed as a one-liner, but this is only for the brave:
document.cookie.split(';').map((x)=>x.split('=')).reduce((accum,current) => { accum[current[0]]=current[1]; return accum;}, {})[name]
The absolute best approach would be to generate cookieDict at page load and then throughout the page lifecycle just access individual cookies by calling cookieDict['cookiename'].
This function doesn't work for older browser like chrome > 80.
const getCookieValue = (name) => (
document.cookie.match('(^|;)\\s*' + name + '\\s*=\\s*([^;]+)')?.pop() || ''
)
I solved it by using this function instead that returns undefined if the cookie is missing:
function getCookie(name) {
// Add the = sign
name = name + '=';
// Get the decoded cookie
var decodedCookie = decodeURIComponent(document.cookie);
// Get all cookies, split on ; sign
var cookies = decodedCookie.split(';');
// Loop over the cookies
for (var i = 0; i < cookies.length; i++) {
// Define the single cookie, and remove whitespace
var cookie = cookies[i].trim();
// If this cookie has the name of what we are searching
if (cookie.indexOf(name) == 0) {
// Return everything after the cookies name
return cookie.substring(name.length, cookie.length);
}
}
}
Credit: https://daily-dev-tips.com/posts/vanilla-javascript-cookies-%F0%9F%8D%AA/
You can verify if a cookie exists and it has a defined value:
function getCookie(cookiename) {
if (typeof(cookiename) == 'string' && cookiename != '') {
const COOKIES = document.cookie.split(';');
for (i = 0; i < COOKIES.length; i++) {
if (COOKIES[i].trim().startsWith(cookiename)) {
return COOKIES[i].split('=')[1];
}
}
}
return null;
}
const COOKIE_EXAMPLE = getCookie('example');
if (COOKIE_EXAMPLE == 'stackoverflow') { ... }
// If is set a cookie named "example" with value "stackoverflow"
if (COOKIE_EXAMPLE != null) { ... }
// If is set a cookie named "example" ignoring the value
It will return null if cookie doesn't exists.
Get the cookie value or undefined if it doesn't exist:
document
.cookie
.split('; ')
.filter(row => row.startsWith('cookie_name='))
.map(c=>c.split('=')[1])[0];
On chromium based browsers you can use the experimental cookieStore api:
await cookieStore.get('cookieName');
Check the Browsersupport before using!