Check returning visitors using cookies - javascript

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

Related

Redirect user to random URL from a list that shrinks upon each visit, then resets

This JavaScript redirects the user to a random URL from a list for 30 days, then randomly assigns a different destination URL:
// List of URLs (two or more) for the experimental treatment and control groups.
var RedirectURLs = {
"urls" : [
{ "url" : "http://www.aftonbladet.se/" },
{ "url" : "http://www.dn.se/" },
{ "url" : "http://www.svd.se/" }
]
}
// Count the number of URLs in list.
var Groups = RedirectURLs.urls.length;
// Randomize number and get the corresponding index for the URL in list.
var gotoUrl = RedirectURLs.urls[GetRandomNumber(Groups)].url
// Perform redirection.
if (window.location.search == "?debug") {
// Debug mode: If user supplies a ?debug querystring,
// then only show the redirect URL, but don't actually redirect.
document.write("Redirect URL: " + gotoUrl);
} else {
// Redirect the user to the new URL.
document.location = gotoUrl;
}
// Perform randomization and save it to a cookie.
function GetRandomNumber(Groups) {
// Has cookie been set?
var rndIndex = null;
if (GetCookie() != "") {
// Yes, get randomization from cookie.
rndIndex = GetCookie()
} else {
// No, set random value to cookie.
rndIndex = Math.floor((Math.random() * Groups));
SetCookie(rndIndex, 30) // Set cookie for 30 days.
}
return rndIndex
}
// Set cookie with randomization value.
function SetCookie(CookieValue, DaysUntilExpire) {
var d = new Date();
d.setTime(d.getTime() + (DaysUntilExpire * 24 * 60 * 60 * 1000));
document.cookie = "rnd=" + CookieValue + ";expires=" + d.toUTCString();
}
// Get cookie with randomization value. Return empty string if not set.
function GetCookie() {
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("rnd=") == 0) return c.substring(4, c.length);
}
return "";
}
How can the code be modified so that instead of storing a cookie that tells the browser to keep going to the same URL for 30 days, instead, the cookie is used to cumulatively track what's already been visited, so the user is redirected to new URL's until each one from list has been visited and tracking starts all over?
For example:
if cookie is empty, user is randomly redirected to link 2 from a list of 4 url's
cookie stores [1,3,4]
next visit, user is randomly redirected to link 4
cookie deletes 4 to become [1,3]
next visit, user is randomly redirected to link 3
cookie deletes 3 to become 1
next visit, user is redirected to link 1
cookie clears
next visit, cookie is empty, so user randomly redirects to link from full list

HTML cookie don't create

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=/";
}

Conditional Cached Page Redirect

I am trying to set up a conditional cached re-direct depending on the website viewers choice.
Here's an example of how I am looking to have the website function ( you can test this by going to vonage.com):
When I visit www.vonage.com, I have a choice between "For Personal, For Small Business, For Mid-Market & Enterprise".
After making the choice, you'll be sent to the associated website/subdomain - either vonage.com, personal.vonage.com, or enterprise.vonage.com.
Then, if you try to go back to the initial page with choices, you won't be able to, you're redirected back to the choice that you've already made.
How is this done? I would like to implement something similar. I'm using Wordpress by the way, but that probably won't matter, I can get my hands dirty in the code or .htaccess.
There may be a better way, and this is java-script only not php, but a cookie should do the trick.
on page load check if the cookie exists, if it does redirect, if not don't:
if (document.cookie.indexOf("home") >= 0) {
// redirect them to home
}
else if (document.cookie.indexOf("business") >= 0) {
// redirect them to business
}
else if (document.cookie.indexOf("enterprise") >= 0) {
// redirect them to enterprise
}
if none of those trigger, and the user is not redirected when they choose an option set their cookie, for example:
// set a new cookie
expiry = new Date();
expiry.setTime(date.getTime()+(10*60*1000)); // Ten minutes
// Date()'s toGMTSting() method will format the date correctly for a cookie
document.cookie = "business; expires=" + expiry.toGMTString();
(function(href, referrer) {
var enterprise = "http://enterprise.mysite.com"
var personal = "http://personal.mysite.com"
var is_enterprise = new RegExp(enterprise).test(href)
var is_personal = new RegExp(personal).test(href)
var cache = readCookie('portal')
if (cache) return location.href = cache
var portal = is_enterprise || is_personal
if (portal) document.cookie = "portal=" + (enterprise || personal) + "; expires=Fri, 31 Dec 9999 23:59:59 GMT";
return null
})(location.href, document.referrer)
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;
}

Client-side JS session library

I'm looking for a client-side JS library to store session variables.
I'd like a library that supports alternative storage medium, e.g. cookies when available with fallback on other techniques.
For instance, I found this one (but the last update is in 2009):
http://code.google.com/p/sessionstorage/
I'm not interested in security (apart a bit of data isolation among applications), as I'm not going to store sensitive data.
To give an example of use case, I want to display a message "Chrome user? Download the app" for chrome users, and I'd like to maintain a status in session to avoid displaying the message again to the same user. I don't want server-side sessions as I have caching enabled, so I must be able to serve the exact same page to different users.
You can use localStorage if available, and if it's not, then using cookies (or whatever you feel to):
var appToken = createToken();
try {
if (localStorage.getItem) {
localStorage.downloadAppAlert = appToken;
} else {
setCookie('downloadAppAlert', appToken, 10); // name, a string value, num. of days
}
} catch(e) {
console.log(e);
}
Then you can use some function to set your cookies - i.e. this one i just found in w3schools:
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;
}
To retrieve a cookie value by it's name - downloadAppAlert in the example - you can use the one on the w3schools link or something like this:
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;
}
Also, to retrieve a previously setted item on the localStorage you simply:
var appToken = localStorage.getItem('downloadAppAlert');
EDIT: Sorry, with the hurries i forgot to mention what createToken() does. It is supposed to be a random alphanumeric generator function. You can find plenty on SO, like:
Random alpha-numeric string in JavaScript?
Generate random string/characters in JavaScript
Generating (pseudo)random alpha-numeric strings
Use node-client-sessions (https://github.com/mozilla/node-client-sessions) by mozilla.

Session only cookies with Javascript

I was wondering if it's possible to create session only cookies with Javascript. When the browser is closed the cookies should be removed.
I can't use anything on the server as the website is HTML only ... so no server side script is used.
I read something about this here:
http://blog.lysender.com/2011/08/setting-session-only-cookie-via-javascript/
but i can't find any more information about this ... so i was wondering if this method is reliable.
Yes, that is correct.
Not putting an expires part in will create a session cookie, whether it is created in JavaScript or on the server.
See https://stackoverflow.com/a/532660/1901857
For the use case in the question (no server side code), sessionStorage is a simpler solution. But sessionStorage is client only, so would not work if you need to access the stored value on the server (e.g. user logins etc.)
A simpler solution would be to use sessionStorage, in this case:
var myVariable = "Hello World";
sessionStorage['myvariable'] = myVariable;
var readValue = sessionStorage['myvariable'];
console.log(readValue);
However, keep in mind that sessionStorage saves everything as a string, so when working with arrays / objects, you can use JSON to store them:
var myVariable = {a:[1,2,3,4], b:"some text"};
sessionStorage['myvariable'] = JSON.stringify(myVariable);
var readValue = JSON.parse(sessionStorage['myvariable']);
A page session lasts for as long as the browser is open and survives over page reloads and restores. Opening a page in a new tab or window will cause a new session to be initiated.
So, when you close the page / tab, the data is lost.
For creating session only cookie with java script, you can use the following. This works for me.
document.cookie = "cookiename=value; expires=0; path=/";
then get cookie value as following
//get cookie
var cookiename = getCookie("cookiename");
if (cookiename == "value") {
//write your script
}
//function getCookie
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) != -1) return c.substring(name.length, c.length);
}
return "";
}
Okay to support IE we can leave "expires" completely and can use this
document.cookie = "mtracker=somevalue; path=/";
Use the below code for a setup session cookie, it will work until browser close. (make sure not close tab)
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 false;
}
if(getCookie("KoiMilGaya")) {
//alert('found');
// Cookie found. Display any text like repeat user. // reload, other page visit, close tab and open again..
} else {
//alert('nothing');
// Display popup or anthing here. it shows on first visit only.
// this will load again when user closer browser and open again.
setCookie('KoiMilGaya','1');
}

Categories