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 found this code for Google Analytics which lets you analyze just a subset of data for your analytics.
_gaq.push(['_setSampleRate', '80']);
I want to do the same thing with Mixpanel but from what I understand SetSampleRate is a function that is specific to Google Analytics.
How might I do something like this in Mixpanel?
I have browsed their KB & Help articles but haven't found anything that talks about this.
All you have to do is create a Random number from 0 to 100 and check if it's lower than the sample target you have. If it's lower you track it, otherwise you don't.
The way _setSampleRate works in Google Analytics is that it samples by user not by hit. So when you generate the Random number you also have to store it in a cookie so that you can check for further interactions and either track it or not.
In the Example below I created a helper function that checks if the user is in the Sample and handles the cookie logic for me.
function inSample(target) {
var domain_name = 'mysite.com'; // CUSTOMIZE WITH YOUR DOMAIN
var sampleCookie = 'mixpanel_sample='; // COOKIE NAME
var current = document.cookie;
if (current.indexOf(sampleCookie) > -1) {
// Cookie already exists use it
var current = document.cookie.substring(
document.cookie.indexOf(sampleCookie) + sampleCookie.length
);
if (current.indexOf(';') > -1)
current = current.substring(0,current.indexOf(';'));
current = parseInt(current);
} else {
// Cookie not found calculate a random number
current = Math.floor(Math.random()*100)
}
// reset the cookie to expire in 2 years
var two_years = new Date();
two_years.setTime(two_years.getTime() + 2*365*24*60*60*1000);
two_years = two_years.toGMTString();
document.cookie = sampleCookie + current +
'; domain=' + domain_name + '; path=/' +
' ; expires=' + two_years + ';'
return target >= current;
}
Now all you have to do is use this function in order to fire or not the mixPanel tracking Code.
if (inSample(80)) {
// MIXPANEL TRACKING CODE GOES HERE
}
What you have in the end is a report in Mixpanel that only includes 80% of your users.
I have set a cookie with document.cookie. The content settings in Google Chrome is showing the cookie. However, document.cookie is displaying as a blank string when printed. Why is this happening?
Here is my code
function setCookie(name,value,lifeTime,path,domain,secure){//lifetime in hours
{
var c_ = name +'='+escape(value)+'; ';
var life = new Date();
lifeTime<1&&lifeTime>0?life.setMinutes(life.getMinutes()+lifeTime*60):life.setHours(life.getHours()+lifeTime);
life = life.toUTCString();
c_+='expires='+life+"; ";
c_+= 'domain='+domain+'; ';
c_ += 'secure=secure; ';//secure
c_ += 'path='+path;
document.cookie = c_;
alert(document.cookie);
/*Just splitted the code instead of c = 'name='+value+'expires ='+life etc*/
}
A possible problem with this function is, it always sets a secure cookie. So, if you've requested/opened the page with HTTP not HTTPS protocol, the secure cookie won't be exposed.
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!
I have set a cookie using
document.cookie =
'MYBIGCOOKIE=' + value +
'; expires=' + now.toGMTString() +
'; path=/';
Now there are between 5 and 10 cookies set on this site, is there a way to check the value ofthis cookie by name.
if (document.cookie.MYBIGCOOKIE == '1') {
alert('it is 1')
}
Use the RegExp constructor and multiple replacements to clarify the syntax:
function getCook(cookiename)
{
// Get name followed by anything except a semicolon
var cookiestring=RegExp(cookiename+"=[^;]+").exec(document.cookie);
// Return everything after the equal sign, or an empty string if the cookie name not found
return decodeURIComponent(!!cookiestring ? cookiestring.toString().replace(/^[^=]+./,"") : "");
}
//Sample usage
var cookieValue = getCook('MYBIGCOOKIE');
Unfortunately, Javascript's cookie syntax is nowhere near as nice as that. In fact, in my opinion, it's one of the worst designed parts.
When you try to read document.cookie, you get a string containing all the cookies set. You have to parse the string, separating by the semicolon ; character. Rather than writing this yourself, there are plenty of versions available on the web. My favourite is the one at quirksmode.org. This gives you createCookie, readCookie and deleteCookie functions.
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);
}
}
}
Source: W3Schools
Edit: as #zcrar70 noted, the above code is incorrect, please see the following answer Javascript getCookie functions
You can use the following function:
function getCookiesMap(cookiesString) {
return cookiesString.split(";")
.map(function(cookieString) {
return cookieString.trim().split("=");
})
.reduce(function(acc, curr) {
acc[curr[0]] = curr[1];
return acc;
}, {});
}
When, called with document.cookie as parameter, it will return an object, with the cookies keys as keys and the cookies values.
var cookies = getCookiesMap(document.cookie);
var cookieValue = cookies["MYBIGCOOKIE"];
using jquery-cookie
I find this library helpful. 3.128 kb of pure convenience.
add script
<script src="/path/to/jquery.cookie.js"></script>
set cookie
$.cookie('name', 'value');
read cookie
$.cookie('name');
One of the shortest ways is this, however as mentioned previously it can return the wrong cookie if there's similar names (MyCookie vs AnotherMyCookie):
var regex = /MyCookie=(.[^;]*)/ig;
var match = regex.exec(document.cookie);
var value = match[1];
I use this in a chrome extension so I know the name I'm setting,
and I can make sure there won't be a duplicate, more or less.
document.cookie="MYBIGCOOKIE=1";
Your cookies would look like:
"MYBIGCOOKIE=1; PHPSESSID=d76f00dvgrtea8f917f50db8c31cce9"
first of all read all cookies:
var read_cookies = document.cookie;
then split all cookies with ";":
var split_read_cookie = read_cookies.split( ";" );
then use for loop to read each value. Into loop each value split again with "=":
for ( i = 0; i < split_read_cookie.length; i++ ){
var value = split_read_cookie[i];
value = value.split( "=" );
if( value[0] == "MYBIGCOOKIE" && value[1] == "1" ){
alert( 'it is 1' );
}
}
The point of Stack Overflow is to provide a database of good quality answers, so I am going to reference some standard source code and an article that gives examples:
http://www.codelib.net/javascript/cookies.html
Note: The code is regular-expression free for greatly enhanced efficiency.
Using the source code provided, you would use cookies like this:
makeCookie('color', 'silver');
This saves a cookie indicating that the color is silver. The cookie would expire after the current session (as soon as the user quits the browser).
makeCookie('color', 'green', { domain: 'gardens.home.com' });
This saves the color green for gardens.home.com.
makeCookie('color', 'white', { domain: '.home.com', path: '/invoices' });
makeCookie('invoiceno', '0259876', { path: '/invoices', secure: true });
saves the color white for invoices viewed anywhere at home.com. The second cookie is a secure cookie, and records an invoice number. This cookie will be sent only to pages that are viewed through secure HTTPS connections, and scripts within secure pages are the only scripts allowed to access the cookie.
One HTTP host is not allowed to store or read cookies for another HTTP host. Thus, a cookie domain must be stored with at least two periods. By default, the domain is the same as the domain of the web address which created the cookie.
The path of an HTTP cookie restricts it to certain files on the HTTP host. Some browsers use a default path of /, so the cookie will be available on the whole host. Other browsers use the whole filename. In this case, if /invoices/overdue.cgi creates a cookie, only /invoices/overdue.cgi is going to get the cookie back.
When setting paths and other parameters, they are usually based on data obtained from variables like location.href, etc. These strings are already escaped, so when the cookie is created, the cookie function does not escape these values again. Only the name and value of the cookie are escaped, so we can conveniently use arbitrary names or values. Some browsers limit the total size of a cookie, or the total number of cookies which one domain is allowed to keep.
makeCookie('rememberemail', 'yes', { expires: 7 });
makeCookie('rememberlogin', 'yes', { expires: 1 });
makeCookie('allowentergrades', 'yes', { expires: 1/24 });
these cookies would remember the user's email for 7 days, the user's login for 1 day, and allow the user to enter grades without a password for 1 hour (a twenty-fourth of a day). These time limits are obeyed even if they quit the browser, and even if they don't quit the browser. Users are free to use a different browser program, or to delete cookies. If they do this, the cookies will have no effect, regardless of the expiration date.
makeCookie('rememberlogin', 'yes', { expires: -1 });
deletes the cookie. The cookie value is superfluous, and the return value false means that deletion was successful. (A expiration of -1 is used instead of 0. If we had used 0, the cookie might be undeleted until one second past the current time. In this case we would think that deletion was unsuccessful.)
Obviously, since a cookie can be deleted in this way, a new cookie will also overwrite any value of an old cookie which has the same name, including the expiration date, etc. However, cookies for completely non-overlapping paths or domains are stored separately, and the same names do not interfere with each other. But in general, any path or domain which has access to a cookie can overwrite the cookie, no matter whether or not it changes the path or domain of the new cookie.
rmCookie('rememberlogin');
also deletes the cookie, by doing makeCookie('rememberlogin', '', { expires: -1 }). This makes the cookie code longer, but saves code for people who use it, which one might think saves more code in the long run.
I use this to read cookie:
function getCookie (key) {
let value = ''
document.cookie.split(';').forEach((e)=>{
if(e.includes(key)) {
value = e.split('=')[1]
}
})
return value
}
let name = getCookie(name)
Using string.match. Returns the cookie or null
function checkForCookie(name) {
let cookieString = document.cookie.match(name + '=[^;]+')
return cookieString ? cookieString[0] : cookieString
}
Here is an example implementation, which would make this process seamless (Borrowed from AngularJs)
var CookieReader = (function(){
var lastCookies = {};
var lastCookieString = '';
function safeGetCookie() {
try {
return document.cookie || '';
} catch (e) {
return '';
}
}
function safeDecodeURIComponent(str) {
try {
return decodeURIComponent(str);
} catch (e) {
return str;
}
}
function isUndefined(value) {
return typeof value === 'undefined';
}
return function () {
var cookieArray, cookie, i, index, name;
var currentCookieString = safeGetCookie();
if (currentCookieString !== lastCookieString) {
lastCookieString = currentCookieString;
cookieArray = lastCookieString.split('; ');
lastCookies = {};
for (i = 0; i < cookieArray.length; i++) {
cookie = cookieArray[i];
index = cookie.indexOf('=');
if (index > 0) { //ignore nameless cookies
name = safeDecodeURIComponent(cookie.substring(0, index));
if (isUndefined(lastCookies[name])) {
lastCookies[name] = safeDecodeURIComponent(cookie.substring(index + 1));
}
}
}
}
return lastCookies;
};
})();
This is my simple solution:
function getCookieValue(userKey){
let items = document.cookie.split(";")
for(item of items){
let [key, value] = item.split("=");
if(key === userKey)
return value;
};
return null;
}
I have come up with confusing yet very simple step after 2 hrs of concentration.
suppose a cookie 'username' is stored with a value 'John Doe'.
Then call readCookies('username'), this function (defined just below ) returns the value 'John Doe'.
function readCookies(requestedKey){
var cookies = document.cookie;
var temporaryKeyIndex=-1,temporaryKeySet=false,temporaryKey,temporaryValue;
var temporaryValueIndex = -1,previousTemporaryValueIndex=-2;
var readableCookie=[];
var a;
for(var i=0;i<cookies.length;i++){
if(cookies[i]!='='&&!temporaryKeySet){
temporaryKeyIndex++;
temporaryValueIndex++;
}
else{
temporaryKeySet = true;
if(cookies[i]==';'||i==(cookies.length-1)){
temporaryKey = cookies.slice(previousTemporaryValueIndex+2,temporaryKeyIndex+1);
if(cookies.length>temporaryValueIndex+2){
temporaryValue = cookies.slice(temporaryKeyIndex+2,temporaryValueIndex+1);
}
else{
temporaryValue = cookies.slice(-((cookies.length-1) - (temporaryKeyIndex+1)))
}
alert('tempkey: '+temporaryKey+', reqKEY: '+requestedKey);
if(requestedKey.trim()==temporaryKey.trim()){
alert(1);
return temporaryValue;
}
previousTemporaryValueIndex = temporaryValueIndex;
temporaryKeyIndex = ++temporaryValueIndex;
temporaryKeySet=false;
}
else{
temporaryValueIndex++;
}
}
}
}
Here is an API which was written to smooth over the nasty browser cookie "API"
https://github.com/jaaulde/cookies
The simplest way to read a cookie I can think is using Regexp like this:
**Replace COOKIE_NAME with the name of your cookie.
document.cookie.match(/COOKIE_NAME=([^;]*);/)[1]
How does it work?
Cookies are stored in document.cookie like this: cookieName=cookieValue;cookieName2=cookieValue2;.....
The regex searches the whole cookie string for literaly "COOKIE_NAME=" and captures anything after it that is not a semicolon until it actually finds a semicolon;
Then we use [1] to get the second item from array, which is the captured group.