UPDATE - made with suggestions from below:
I have the following script that pops up a window, after 3 visits, and to only 20% of visitors. The expiration date is set and shows in Developer tools for expiring in 180 days, but it's still popping up. What am I doing wrong? Any help is appreciated, I do not know javascript at all very well. This has to be done all in plain javascript - no jQuery
//setting the expiration date to 6 months from now//
expDate = new Date;
// in the following line, 180 means 180 days.//
expDate.setTime(expDate.getTime() + 180 * 24 * 60 * 60 * 1000);
expDate.toGMTString();
//making the cookie//
function setCookie(name, value, expires, path, domain, secure) {
document.cookie = name + "=" + escape(value) +
((expires) ? "; expires=" + expires.toGMTString() : "") +
((path) ? "; path=/wmb" + path : "") +
((domain) ? "; domain=www.example.com" + domain : "") +
((secure) ? "; secure" : "");
}
function getCookie(name) {
var dc = document.cookie;
var prefix = name + "=";
var begin = dc.indexOf("; " + prefix);
if (begin == -1) {
begin = dc.indexOf(prefix);
if (begin != 0) return null;
} else {
begin += 1;
}
var end = document.cookie.indexOf(";", begin);
if (end == -1) {
end = dc.length;
}
return unescape(dc.substring(begin + prefix.length, end));
}
//cookie name is called CustomSurvey//
visits = getCookie('CustomSurvey');
if (!visits) {
visits = 1
};
if (visits < 4)
//Math.random is set so that 20% of those visits actually get the popup//
if ((Math.random() * (100 - 1) + 1) < 20) {
//get location of where this popup came from; also contains variable from SM that will trickle down into reporting to tell where it came from//
var currentLocation = window.location;
window.open("https:mysurvey.com" + "_blank", "toolbar=yes,scrollbars=yes,resizable=yes,top=500,left=500,width=400,height=400");
}
if (visits < 3) {
++visits;
cookieData = visits;
setCookie('CustomSurvey', cookieData, expDate)
}
I changed to what you suggested (except the url - that part is just made up (the real one pops up). I did everything suggested except when I changed the visits > 3 , now nothing pops up (after clearing cache and clicking about 50 times.
This is what I have now:
//setting the expiration date to 6 months from now//
expDate = new Date;
// in the following line, 180 means 180 days.//
expDate.setDate(expDate.getDate() + 180)
//making the cookie//
function setCookie(name, value, expires, path, domain, secure){
document.cookie= name + "=" + escape(value) +
((expires) ? "; expires=" + expires.toGMTString() : "") +
((path) ? "; path=/wmb" + path : "") +
((domain) ? "; domain=ptoweb.uspto.gov" + domain : "") +
((secure) ? "; secure" : "");
}
function getCookie(name) {
var dc = document.cookie;
var prefix = name + "=";
var begin = dc.indexOf("; " + prefix);
if (begin == -1) {
begin = dc.indexOf(prefix);
if (begin != 0) return null;
} else {
begin += 1;
}
var end = document.cookie.indexOf(";", begin);
if (end == -1) {
end = dc.length;
}
return unescape(dc.substring(begin + prefix.length, end));
}
//cookie name is called CustomSurvey//
visits = getCookie('CustomSurvey');
if (!visits) {
visits = 1
};
if (visits > 3)
//Math.random is set so that 20% of those visits actually get the popup//
if ((Math.random() * (100 - 1) + 1) < 20) {
//get location of where this popup came from; also contains variable from SM that will trickle down into reporting to tell where it came from//
var currentLocation = window.location;
window.open("https://www.surveymonkey" + "?" + currentLocation, "_blank", "toolbar=yes,scrollbars=yes,resizable=yes,top=500,left=500,width=400,height=400");
}
if (visits < 3) {
++visits;
cookieData = visits;
setCookie('CustomSurvey', cookieData, expDate)
}
Related
The Logic: Someone open my LP (landing page) first time > he closes my LP and go away > he open my LP second time.
So, how can i redirect him to another URL when he opens my Landing page second time?
P.S. I'm a newbie, so better for me is using cookies.
I have been searching stackoverflow and did not find an answer for exactly my question
function setCookie(cookie_name, value, days) {
var exdate = new Date();
exdate.setDate(exdate.getDate() + days);
var cookie_value = escape(value) + ((days == null) ? '' : ';
expires=' + exdate.toUTCString());
document.cookie = cookie_name + '=' + cookie_value;
}
function getCookie(cookie_name) {
var x, y;
var val = document.cookie.split(';');
for (var i = 0; i < val.length; i++) {
x = val[i].substr(0, val[i].indexOf('='));
y = val[i].substr(val[i].indexOf('=') + 1);
x = x.replace(/^\s+|\s+$/g, '');
if (x == cookie_name) {
return unescape(y);
}
}
}
if (getCookie("isVisited") === "true") {
window.location.href = "https://redirect-url";
}
I'm not great with javascript, but I have one that is working, but it seems like it's not following the 6 month expiration date that I set. Can someone help troubleshoot? This is what I have when setting the cookie's expiration date:
expDate = new Date;
// in the following line, 180 means 180 days.
expDate.setTime(expDate.getTime() + 180 * 24 * 60 * 60 * 1000);
expDate.toGMTString();
function setCookie(name, value, expires, path, domain, secure){
document.cookie= name + "=" + escape(value) +
((expires) ? "; expires=" + expires.toGMTString() : "") +
((path) ? "; path=" + path : "") +
((domain) ? "; domain=" + domain : "") +
((secure) ? "; secure" : "");
}
function getCookie(name){........
Any help troubleshooting would be perfect and very appreciated!
UPDATE - here is the script in its entirety. I'm calling a pop-up window only to show if it's been 3 page visits, and 20%, and 6 months expiration date. Just piecing it together so take it easy on me!!
expDate = new Date;
// in the following line, 180 means 180 days.
expDate.setTime(expDate.getTime() + 180 * 24 * 60 * 60 * 1000);
expDate.toGMTString();
function setCookie(name, value, expires, path, domain, secure){
document.cookie= name + "=" + escape(value) +
((expires) ? "; expires=" + expires.toGMTString() : "") +
((path) ? "; path=" + path : "") +
((domain) ? "; domain=" + domain : "") +
((secure) ? "; secure" : "");
}
function getCookie(name){
var dc = document.cookie;
var prefix = name + "=";
var begin = dc.indexOf("; " + prefix);
if (begin == -1){
begin = dc.indexOf(prefix);
if (begin != 0) return null;}
else{begin += 2;}
var end = document.cookie.indexOf(";", begin);
if (end == -1){end = dc.length;}
return unescape(dc.substring(begin + prefix.length, end));
}
visits = getCookie('nVisits');
if (!visits) {
visits = 1
};
if (visits == 3)
if ((Math.random() * (100 - 1) + 1) < 20)
{
window.open("https://mypoup.html", "_blank", "toolbar=yes,scrollbars=yes,resizable=yes,top=500,left=500,width=400,height=400");
}
if (visits < 3) {
++visits;
cookieData = visits;
setCookie('nVisits', cookieData, expDate)
}
Kaddath's comment solved the problem:
it seems that toGMTString() is obsolete and should not be used anymore, use toUTCString() instead.
I am trying to make a pop-up that only shows up:
after the third visit, and only 20% of the time.
I have this right now, and I'm not really great at Javascript and need some help figuring out exactly what I'm doing wrong. Any help would be appreciated
visits = getCookie('nVisits');
if (!visits) {
visits = 1
}
if (visits == 3) {
deleteCookie('nVisits')
if (rand(0, 100) <= 20) {
window.open("http://mypopup.html", "_blank", "toolbar=yes,scrollbars=yes,resizable=yes,top=500,left=500,width=400,height=400");
} else {
if (visits < 3) {
++visits;
cookieData = visits;
setCookie('nVisits', cookieData, expDate)
}
}
}
In the head of the page I set the cookie:
expDate = new Date;
// in the following line, 180 means 180 days.
expDate.setTime(expDate.getTime() + 180 * 24 * 60 * 60 * 1000); expDate.toGMTString();
function setCookie(name, value, expires, path, domain, secure){
document.cookie= name + "=" + escape(value) +
((expires) ? "; expires=" + expires.toGMTString() : "") +
((path) ? "; path=" + path : "") +
((domain) ? "; domain=" + domain : "") +
((secure) ? "; secure" : "");
}
function getCookie(name){
var dc = document.cookie;
var prefix = name + "=";
var begin = dc.indexOf("; " + prefix);
if (begin == -1){
begin = dc.indexOf(prefix);
if (begin != 0) return null;}
else{begin += 2;}
var end = document.cookie.indexOf(";", begin);
if (end == -1){end = dc.length;}
return unescape(dc.substring(begin + prefix.length, end));
}
function deleteCookie(name, path, domain){
if (getCookie(name)){
document.cookie = name + "=" +
((path) ? "; path=" + path : "") +
((domain) ? "; domain=" + domain : "") +
"; expires=Thu, 01-Jan-70 00:00:01 GMT";}
}
----UPDATE---
I originally had this - which was working - it's just getting the random 20% to work...
<Script>
visits = getCookie('nVisits');
if (!visits){visits = 1};
if (visits == 3 ){deleteCookie('nVisits')
window.open("https://popup.html", "_blank", "toolbar=yes,scrollbars=yes,resizable=yes,top=500,left=500,width=400,height=400");
}
if (visits < 3){++visits;
cookieData = visits;
setCookie('nVisits',cookieData,expDate)
}
</Script>
Because I couln't find the definition for your function rand, I completely rewrote the snipped.
const visitsCookieName = 'nVisits';
let visits = getCookie(visitsCookieName) || 0;
if (visits === 3) {
deleteCookie(visitsCookieName)
if (Math.floor(Math.random() * 5)) return;
window.open("http://mypopup.html", "_blank", "toolbar=yes,scrollbars=yes,resizable=yes,top=500,left=500,width=400,height=400");
return;
}
setCookie(visitsCookieName, ++visits, expDate);
Explanation
The random logic I'm using here is really simple. First I multiply the random float to 5 which return a float number between 0 and ~4.99. After that we need the floored value of it. So it's between 0 and 4. Because 0 == false this hit only 20% of all tries.
Another problem in your snipped is on line 10 (if (visits < 3) {). This will never be true because in the upper statement you check if if (visits == 3) { (line 5) and because you didn't change the value of visits it can't be anything else but exactly 3.
What i am trying to accomplish :
When a href is pressed i call the saveItem() function. It is called as below :
<a href="#" class="save-product" onclick="saveItem('savedList', '<?php echo get_the_ID();?>', 90)">
savedList = the name of my cookie
get_the_ID() = A wordpress function to get the current's ID post, '185' etc.
90 = the days for the cookie to expire
When saveItem() is called, it checks if a cookie with name savedList already exists. If it doesn't, it creates a cookie with that name and adds the value which is passed through the parameter(the id of current post).
When this cookie exists, i want to add to that cookie one more id and the delimiter would be ; so i can - in another page show a list of products through that cookie's list.
So my cookie has "185" . When i add a new ID, for example "65", i want my cookie to become "185;65"
My problem is that it doesn't work as expected. The weird thing is that if i see on the console.log("New Value Is : " + newValue); it shows "185;65" but
console.log(mNameList); shows only "185" again.
To check my cookie's value i use :
print_r($_COOKIE['savedList']);
Functions below :
saveItem():
function saveItem(name,value,days) {
var expires = "";
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days*24*60*60*1000));
expires = "; expires=" + date.toUTCString();
}
// Get Cookie
var mNameList = getCookie(name);
// If cookie is empty - doesn't exist then create it and put the value given
if (mNameList == "") {
document.cookie = name + "=" + value + expires + "; path=/";
} else {
// If cookie exists, check if it has already this value, if it doesn't then add oldvalue + new value to that cookie.
if(mNameList !== value){
var newValue = mNameList + ';' + value; // "185;65"
document.cookie = name + "=" + newValue + expires + "; path=/";
console.log("New Value Is : " + newValue);
var mNameList = getCookie(name); // Το check current cookie get it again
console.log(mNameList); // Show it - here it shows "185"
}
else{
// Value already exists in cookie - don't add it
console.log("Are same - mNameList->" + mNameList + " | currentID->" + value);
}
}
}
Getcookie();
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 "";
}
As you do it yourself ; is the field delimiter in a cookie between value, expiration etc. You cannot use it to seperate your values.
Ok so the problem was in the delimiter and in my code too - the way i was checking if ID already exists was wrong but the below works.
saveItem()
function saveItem(name,value,days) {
var expires = "";
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days*24*60*60*1000));
expires = "; expires=" + date.toUTCString();
}
var mNameList = getCookie(name);
if (mNameList == "") {
document.cookie = name + "=" + value + expires + "; path=/";
} else {
var doesItemExists = false;
var partsOfStr = mNameList.split('-');
for(var i =0; i < partsOfStr.length; i++){
if(partsOfStr[i] == value)
doesItemExists = true;
}
if(!doesItemExists){
var newValue = mNameList + '-' + value;
document.cookie = name + "=" + newValue + expires + "; path=/";
console.log("New Value Is : " + newValue);
}
else{
console.log("Are same - mNameList->" + mNameList + " | currentID->" + value);
}
}
}
I am having trouble setting and deleting cookies in php Ive got no problem.. in javascript eh.. lots I know this question is everywhere but all the answers I come across seem to bring me the same fate so I have no idea whats going on.. this is what I have currently.
SetCookie("username",ztsUser,14,'/', '');
function SetCookie (name,value,expires,path,domain,secure) {
document.cookie = name + "=" + escape (value) +
((expires) ? "; expires=" + expires.toGMTString() : "") +
((path) ? "; path=" + path : "") +
((domain) ? "; domain=" + domain : "") +
((secure) ? "; secure" : "");
}
the error:
expires.toGMTString is not a function
The whole lot of cookie functions I have.. is:
var today = new Date();
var expiry = new Date(today.getTime() + 365 * 24 * 60 * 60 * 1000);
function getCookieVal (offset) {
var endstr = document.cookie.indexOf (";", offset);
if (endstr == -1) { endstr = document.cookie.length; }
return unescape(document.cookie.substring(offset, endstr));
}
function GetCookie (name) {
var arg = name + "=";
var alen = arg.length;
var clen = document.cookie.length;
var i = 0;
while (i < clen) {
var j = i + alen;
if (document.cookie.substring(i, j) == arg) {
return getCookieVal (j);
}
i = document.cookie.indexOf(" ", i) + 1;
if (i == 0) break;
}
return null;
}
function DeleteCookie (name,path,domain) {
if (GetCookie(name)) {
document.cookie = name + "=" +
((path) ? "; path=" + path : "") +
((domain) ? "; domain=" + domain : "") +
"; expires=Thu, 01-Jan-70 00:00:01 GMT";
}
}
function SetCookie (name,value,expires,path,domain,secure) {
document.cookie = name + "=" + escape (value) +
((expires) ? "; expires=" + expires.toGMTString() : "") +
((path) ? "; path=" + path : "") +
((domain) ? "; domain=" + domain : "") +
((secure) ? "; secure" : "");
}
if anyone knows a better method Im all ears.. but this is what I got at the moment, I need to set, update, delete, get the value of.. cookies
toGMTString has been deprecated. Try toUTCString instead:
function SetCookie (name,value,expires,path,domain,secure) {
document.cookie = name + "=" + escape (value) +
((expires) ? "; expires=" + expires.toUTCString() : "") +
((path) ? "; path=" + path : "") +
((domain) ? "; domain=" + domain : "") +
((secure) ? "; secure" : "");
}
You're also passing a number (14) when the function expects a Date (expires.toUTCString):
SetCookie("username", ztsUser, 14, '/', '');
What is 14 intended to be? 14 days? Assuming that, you can add this at the top of the function to support both numbers and dates:
if ('number' === typeof expires) {
expires = new Date(new Date().getTime() + expires * 86400000);
}
86400000 is the number of milliseconds in a day -- 24 * 60 * 60 * 1000.
There are already a number of great libraries for handling cookies in JS. Why not use one of them? Just go to your favorite search engine and enter "javascript cookie library" to find one.