JavaScript redirect based on presence of cookie - javascript

I am trying to set up a system where a cookie is created when ever a user lands on a specific page.
for example:
if a user goes to .com/jp/a3 a cookie is created.
I am using this code to create the cookie and it seems to be creating the cookie on that page.
<script>
document.cookie = "name_of_cookie=a3; expires=31 Dec 2017 12:00:00 UTC; path=/"
</script>
I currently have pages .com/jp/a1 through .com/jp/a3 created. So there is a possibility of three cookies being created.
Upon the user's next visit, I would like the browser to check for these cookies and redirect back to that page when a user visits the normal landing page. If a user has been to multiple pages, I would like the priority to be set to the page they visited first. (this may involve coding some if else statements into my javascript to set the cookie I assume?) If this is difficult, I would be ok with just moving through the a1-a3 list as a1 having the highest priority and a3 the lowest.
I have tried adding the following code to my website.com/index.html file but am not having any luck.
<script>
function getCookie(cname) {
var name = name_of_cookie + "=";
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 checkCookie() {
var redirect = getCookie("name_of_cookie");
if (redirect != "") {
window.location = "http://www.website.com/jp/" + redirect;
} else {
window.location = "http://www.website.com/"
}
}
checkCookie();
</script>
One issue I think I may be facing, is that while I am on the a3.com pages, I am able to see the cookie in my storage, however, when I go to my index.html page, I am not able to see the cookie in my storage.
I have set the path to /, will this only make the cookie available in the .com/jp/ subfolder, or should it be accessible on the .com/index.html page?
Thank you in advance for any assistance anyone could provide.

You seem to have the getCookie function defined wrong. when testing it, I got the error name_of_cookie is not defined. It seems that on the first line of your getCookie() function, you used name_of_cookie instead of cname as you defined the parameter getCookie(cname)
All you have to do is change it to
var name = cname + "=";
Also, by specifying the path as / you should be able to see the cookies from your index too.

Simple mistake!
I forgot quotations around name_of_cookie in the second line.
Corrected answer is:
<script>
function getCookie(cname) {
var name = "name_of_cookie" + "=";
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 checkCookie() {
var redirect = getCookie("name_of_cookie");
if (redirect != "") {
window.location = "http://www.website.com/jp/" + redirect;
} else {
window.location = "http://www.website.com/"
}
}
checkCookie();
</script>
Thanks for the assistance everyone!

Related

How to get Cookie set with Response.SetCookie(cookie) from Asp MVC using javascript

I have set my cookie in the login section like so:
var cookie = new HttpCookie("sys_user_id", (query.UserAccountId).ToString())
{
Expires = DateTime.Now.AddDays(1)
};
Response.SetCookie(cookie);
I can access and change to integer the same cookie at the view using this code:
<script>
var sysUserId = #Convert.ToInt32(HttpContext.Current.Request.Cookies["sys_user_id"].Value);
</script>
but if I put this in a .js file, I get error at #Convert.ToInt32(HttpContext.Current.Request.Cookies["sys_user_id"].Value);. It is because the .js file cannot read the razor syntax. Is there a way to get my "sys_user_id" cookie and convert it to an integer using javascript so I can place it in my .js file?
For those who have not yet got the answer to this kind of question, this is how I did it.
I created a new function like so:
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 "";
}
then I called my "sys_user_id" cookie using this code:
var sysUserId = getCookie("sys_user_id);
This is the post for this answer:
How to get server side cookies value in javascript?

Show different HTML code after one visit

Only using Javascript, can someone create a html file that uses "XY" html code when the user first visits it, but it should use "ZQ" (so a fully other one) html code after the first visit? So in the second, third, etc. visit of the same user. There could be many users.
Question: how would that html file look like? How to do it? Is it possible using only javascript?
You can use either Cookies or LocalStorage, where the LocalStorage is easier to implement, but requires the latest browser, and users may disable cookies for privacy reasons.
Cookies
function setCookie(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 getCookie(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;
}
// First Visit
if (getCookie("visited") == null) {
// XY code.
alert("XY Code here");
// set the cookie
setCookie("visited", "yes", 10);
} else {
// subsequent visit.
// ZQ code.
alert("ZQ Code here");
}
LocalStorage
if (typeof(Storage) !== "undefined") {
if (localStorage.getItem("visited") == "yes") {
// subsequent visit.
// ZQ code.
alert("ZQ Code here");
} else {
// XY code.
alert("XY Code here");
// set the cookie
localStorage.setItem("visited", "yes");
}
} else {
// Sorry! No Web Storage support..
// Use the above cookie method.
}

avoiding setting a cookie based on a specific URL string

I am setting up a cookie based on the user first visit on a website. So every time a new user visit the website I am redirecting them to the landing page otherwise the user will see the index page directly (since time time the cookie is already in the user's browser).
Now what I am trying to achieve is that I would like skip the landing page redirect based on a specific URL (for both new users and existing users).
This is how I am checking the new visit and setting up a redirect cookie.
$(document).ready(function() {
landingPageOnFirstVisit();
createCookie('landingRedirect', 'true', '60');
});
function landingPageOnFirstVisit() {
var setCookieForLanding = readCookie('landingRedirect');
if (!setCookieForLanding) {
window.location = "/en/landing";
}
}
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;
}
How do I make sure that if user visit the website directly using the below mentioned URL pattern: the redirection process would not occur and we wont set any cookies.
https://www.domain.com/en/page?usePromo=XXXXXX
(where XXXXXX are numbers and changes everytime)
Try
$(function() {
if (location.href.indexOf("usePromo")==-1) {
landingPageOnFirstVisit();
createCookie('landingRedirect', 'true', '60');
}
});

Perform Something when Cookie is set

I have a third-party tracking script enabled on my site. This java-script basically adds a cookie on the first visit and in the subsequent visits it tracks the site.
I have en edge-case scenario(the first page load during which the tracking script adds the cookie for the first time) where on the very first page load I need to perform some operation once the cookie is set. But since I am using a third party tracking code, I cannot change that code and need to know when that script sets the cookie on the page. If I know when the cookie is set then I will write some javascript code to perform some operation based on this cookie value.
Mymodule.cookieReady = function () {
myCookie = Mymodule.getCookie('xyz');
if (cookieReadySet) {
clearTimeout(cookieReadySet);
}
cookieReadySet = setTimeout(Mymodule.cookieReady, 10);
return cookieReadySet;
};
Mymodule.getCookie = function(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 "";
}

Read a cookie when implementing inside of another function

I have the following function to change stylesheets on my website that I want to use cookies to keep stylesheet theme persistent across pages.
<script type="text/javascript">
var i=1;
function styleSheet(){
if(i%2==0){
swapper('css/main.css');
document.cookie = "username=Visitor";
}
else{
swapper('css/stylesheetalternate.css');
document.cookie = "username=alternateVisitor";
}
i++;
}
<button onclick="styleSheet()">Click me</button>
I'm already setting my cookies inside of this function. I'm not too interested in setting expiration dates or anything like that, the default is fine for me. What I do want to try doing however is read the cookies inside of this function each time that I use the button I created. Is there no way to read it inside of the same function?
I'm aware that there exists a jquery library that does this, but I don't want to use jquery if I can get a better performance with javascript.
EDIT:
<script type="text/javascript">
var i=1;
function styleSheet(){
if(i%2==0){
swapper('css/main.css');
document.cookie = "username=Visitor";
readCookie(Visitor);
}
else{
swapper('css/stylesheetalternate.css');
document.cookie = "username=alternateVisitor";
readCookie(alternateVisitor);
}
i++;
}
Do you mean something like the following when you say to use readCookie inside of my function? What I notice from this sort of implementation is that after swapping stylesheets once, it is for whatever reason impossible to swap again until the page is reloaded.
Here's a set of plain javascript cookie functions that you can use from any function. So, to your question, you can call readCookie("username") from your function (or read any other cookie value):
// 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);
}
document.cookies is just a big list of all the cookies. You can parse through it to find the one you're interested in:
function getCookieValue(cookieName) {
var value = null;
document.cookie.split(';')
.forEach(function(pair){
var pairArray = pair.split('=');
if (pairArray[0]==cookieName) {
value = pairArray[1];
}
});
return value;
}
(Untested, let me know how it goes.)

Categories

Resources