Only overwriting cookie when other parameters are present - javascript

I'm trying to store cookies for four different parameters in a URL. I have it working where it'll detect if the cookie is present, if it isn't, it'll add it. I also have it set detect if they come in from another URL string with those parameters but they're different–it'll overwrite the old cookie with the new cookie information, and if the parameter is blank, it'll return null.
The thing I'm having trouble implementing is that I ONLY want it replacing the cookies if the URL string contains a different set of parameters where one at least one of them isn't null. If all four parameters are null, but there are cookies stored, I don't want it replacing the cookie.
Here's the script I have:
function queryParam(name, url) {
if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
}
var source = queryParam('utm_source');
var campaign = queryParam('utm_campaign');
var medium = queryParam('utm_medium');
var content = queryParam('utm_content');
function setCookie(utm, utmvar, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
var expires = "expires="+d.toUTCString();
document.cookie = utm + "=" + utmvar + ";" + expires + ";path=/";
}
function getCookie(utm) {
var name = utm + "=";
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 "";
}
function checkCookie() {
var utmSource = getCookie("utm_source");
if (utmSource != "") {
if (utmSource = source) {
utmSource = utmSource;
}
else {
setCookie("utm_source", utmSource, 7);
}
}
else {
utmSource = source;
if (utmSource != "" && utmSource != null) {
setCookie("utm_source", utmSource, 7);
}
}
var utmCampaign = getCookie("utm_campaign");
if (utmCampaign != "" ) {
if (utmCampaign = campaign) {
utmCampaign = utmCampaign;
}
else {
setCookie("utm_campaign", utmCampaign, 7);
}
}
else {
utmCampaign = campaign;
if (utmCampaign != "" && utmCampaign != null) {
setCookie("utm_campaign", utmCampaign, 7);
}
}
var utmMedium = getCookie("utm_medium");
if (utmMedium != "" ) {
if (utmMedium = medium) {
utmMedium = utmMedium;
}
else {
setCookie("utm_medium", utmMedium, 7);
}
}
else {
utmMedium = medium;
if (utmMedium != "" && utmMedium != null) {
setCookie("utm_medium", utmMedium, 7);
}
}
var utmContent = getCookie("utm_content");
if (utmContent != "") {
if (utmContent = content) {
utmContent = utmContent;
}
else {
setCookie("utm_content", utmContent, 7);
}
}
else {
utmContent = content;
if (utmContent != "" && utmContent != null) {
setCookie("utm_content", utmContent, 7);
}
}
var sbaValue = utmCampaign + ";" + utmSource + ";" + utmMedium + ";" + utmContent;
$("#00N0B000005VTnf").attr("value", sbaValue);
}
So an example of how I want to act would be - if the URL string is:
domain.com/?utm_source=b&utm_medium=a&utm_campaign=c&utm_content=d => sbaValue = a;b;c;d
Then they come in at:
domain.com/?utm_medium=a&utm_campaign=c&utm_content=d => sbaValue = a;null;c;d
Then they come in at:
domain.com/ => sbaValue = a;null;c;d (nothing changes from before)
I tried setting a variable when something isn't null, but no matter how I implemented it, I couldn't get it to work.

if(["utm_campaign","utm_whatever"].some(el=>queryParam(el)){
... change
}
Simply check if there are params before doing the cookiestuff...
By the way, you can safe much time using the OR operator:
setCookie("utm_source",queryParam("utm_source")||getCookie("utm_source")||alternative, 7);

I ended up rewriting a lot of it and cleaned it up A LOT. Here's the final solution:
function queryParam(name, url) {
if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
}
function setCookie(utm, utmvar, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
var expires = "expires="+d.toUTCString();
document.cookie = utm + "=" + utmvar + ";" + expires + ";path=/";
}
function getCookie(utm) {
var name = utm + "=";
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 "";
}
function getQueryStringVariables(){
return {
source: queryParam('utm_source'),
campaign: queryParam('utm_campaign'),
medium: queryParam('utm_medium'),
content: queryParam('utm_content'),
}
}
function isQueryStringSet(){
var queryStringVariables = getQueryStringVariables();
if (queryStringVariables.source ||
queryStringVariables.campaign ||
queryStringVariables.medium ||
queryStringVariables.content) {
return true;
}
return false;
}
function fetchCookieData() {
return {
source: getCookie("utm_source"),
campaign: getCookie("utm_campaign"),
medium: getCookie("utm_medium"),
content: getCookie("utm_content"),
};
};
function updateCookie() {
var queryStringVariables = getQueryStringVariables();
if (isQueryStringSet()) {
setCookie("utm_source", queryStringVariables.source, 7);
setCookie("utm_campaign", queryStringVariables.campaign, 7);
setCookie("utm_medium", queryStringVariables.medium, 7);
setCookie("utm_content", queryStringVariables.content, 7);
}
}
function updateFormValue() {
var cookieData = fetchCookieData();
var sbaValue = cookieData.campaign + ";" + cookieData.source + ";" + cookieData.medium + ";" + cookieData.content;
$("#00N0B000005VTnf").attr("value", sbaValue);
}
updateCookie();
updateFormValue();

Related

Redirect to page if cookie is not found

If a cookie for example
visited
was not found, is it possible to make the page redirect to
/welcome
I have started off with this:
function getCookie(visited) {
var dc = document.cookie;
var prefix = visited + "=";
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 decodeURI(dc.substring(begin + prefix.length, end));
}
function doSomething() {
var myCookie = getCookie("visited");
if (myCookie == null) {
window.location.href = '/welcome';
}
else {
}
}
Have I done this correctly becuase it is not working correctly on my website.
Try PHP:
if (!isset($_COOKIE['visited'])) {
header("Location: page.php");
}
Try using this checkCookie function below
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 "";
}
function checkCookie() {
var visited = getCookie("visited");
if (visited != "") {
// do whatever
} else {
setCookie("visited", "true", 30);
window.location.href = '/welcome';
}
}
For more information, I suggesting visiting W3Schools or MDN

Cookie in html webview android

Hi I need to know is how to read cookies on a html web-view . I have a banner to close it generates a cookie and the idea would be to go to another page that has the banner he would read the cookie to see if the User already have clicked ...
this is the cookie code
function createCookie() {
var d = new Date();
d.setTime(d.getTime() + (1*24*60*60*1000));
var expires = "expires="+d.toUTCString();
document.cookie = "cookie=cookie ; " + expires+';path = http://www.pitstop.com.br/';
document.getElementById('banner_id').style.display='none';
}
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 null;
}
function banner_cookie(){
var teste = getCookie('cookie');
if(teste !=null){
alert(teste);
document.getElementById('banner_id').style.display='none';
}else{
document.getElementById('banner_id').style.display
}
}
You have many issues that seems to stem from wishful thinking and misunderstanding.
For example your path is wrong and you need to pass a name to the cookie script instead of hardcoding the name "cookie"
You need to take a well tested cookie script and use it properly.
function getCookie(name) {
var start = document.cookie.indexOf(name + "=");
var len = start + name.length + 1;
if ((!start) && (name != document.cookie.substring(0, name.length))) {
return null;
}
if (start == -1) return null;
var end = document.cookie.indexOf(';', len);
if (end == -1) end = document.cookie.length;
return unescape(document.cookie.substring(len, end));
}
function setCookie(name, value, expires, path, domain, secure) {
var today = new Date();
today.setTime(today.getTime());
if (expires) {
expires = expires * 1000 * 60 * 60 * 24;
}
var expires_date = new Date(today.getTime() + (expires));
document.cookie = name + '=' + escape(value) +
((expires) ? ';expires=' + expires_date.toGMTString() : '') + //expires.toGMTString()
((path) ? ';path=' + path : '') +
((domain) ? ';domain=' + domain : '') +
((secure) ? ';secure' : '');
}
function deleteCookie(name, path, domain) {
if (getCookie(name)) document.cookie = name + '=' +
((path) ? ';path=' + path : '') +
((domain) ? ';domain=' + domain : '') +
';expires=Thu, 01-Jan-1970 00:00:01 GMT';
}
Your script:
function banner_cookie(){
var teste = getCookie('showbanner')=="true";
document.getElementById('banner_id').style.display=teste?"block":"none";
}
and to set:
setCookie("showbanner","true",14,"/"); // 2 weeks accessible to all website
and to remove
deleteCookie("showbanner","/");

My cookie values are not updating/changing

I am brand new to JavaScript and I am stuck with this code that I created to display the cookie username and the hit count. The problem is that the cookie values are not being updates when using the setCookies() function, but the same values are outputted again and again. Please help me fix it.
function setCookie(cname, cvalue, exdays, visits) {
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires="+d.toUTCString();
var visit = visits.toString()
document.cookie = cname + "=" + cvalue + "; " + expires + "; visits=" + visit;
}
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 "";
}
function checkCookie() {
var user = getCookie("username");
var visitCount = getCookie("visits");
var visitCountConverted = Number(visitCount);
if (visitCountConverted == "") {
visitCountConverted = 1;
}
else if (visitCountConverted >= 1){
visitCountConverted += 1;
}
if (user != "") {
alert("Cookie: " + user + "\n" + "Visits: " + visitCountConverted);
setCookie("username", user, 365, visitCountConverted);
} else {
user = "TheName"; alert("Cookie: " + user + "\n" + "Visits: " + visitCountConverted); setCookie("username", user, 365, visitCountConverted);
}
}
Thank you very much.
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 ;
}
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 "";
}
function checkCookie() {
var user = getCookie("username");
var visitCount = getCookie("visits");
var visitCountConverted = Number(visitCount);
if (visitCountConverted == "") {
visitCountConverted = 1;
}
else if (visitCountConverted >= 1){
visitCountConverted += 1;
}
if (user == "") {
user = "TheName";
setCookie("username", user, 365);
}
alert("Cookie: " + user + "\n" + "Visits: " + visitCountConverted);
setCookie("visits", visitCountConverted, 365);
}
checkCookie();//make sure to call this method so that cookies get set
You was not setting the visit counter cookie I have refactored your code as well so please give it a go

How to set and read cookies JavaScript

I'm trying to make a popup that appears on my site the first time you visit it. But not any other time after that. So I'm trying to make it with cookies. But I'm having absolutely no luck.
I've tried following W3 school's tutorial but I haven't gotten anywhere.
What I'm doing is when the user closes the dialog, it sets a cookie. And I'm trying to make it so when you come back, the pop up doesn't appear because the cookie is set.
Here's my code.
function setCookie(cname,cvalue,exdays) {
var d = new Date();
d.setTime(d.getTime()+(exdays*24*60*60*1000));
var expires = "expires="+d.toGMTString();
document.cookie = cname + "=" + cvalue + "; " + expires;
}
function getCookie(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 "";
}
function checkCookie() {
var username=getCookie("username");
if (username!="") {
$('#firsttimee').css({display : 'none'});
} else {
if (username=="" || username==null) {
$('#firsttimee').css({display : 'block'});
}
}
}
function closepop(){
$('#firsttimee').css({display : 'none'});
var username = 'seen';
setCookie("username",username,365);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="firsttimee">
<div id="firsttimetxt">
<center>
Click here.<br><br>
Done
</center>
</div>
</div>
Thanks in advance! :)
Here is a jsfidddle of my current work, for some reason when you click done the popup doesn't go away..
Use the cookie script from MDN, not W3Schools, looks like W3Schools is not setting the path.
var docCookies = {
getItem: function (sKey) {
return decodeURIComponent(document.cookie.replace(new RegExp("(?:(?:^|.*;)\\s*" + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=\\s*([^;]*).*$)|^.*$"), "$1")) || null;
},
setItem: function (sKey, sValue, vEnd, sPath, sDomain, bSecure) {
if (!sKey || /^(?:expires|max\-age|path|domain|secure)$/i.test(sKey)) { return false; }
var sExpires = "";
if (vEnd) {
switch (vEnd.constructor) {
case Number:
sExpires = vEnd === Infinity ? "; expires=Fri, 31 Dec 9999 23:59:59 GMT" : "; max-age=" + vEnd;
break;
case String:
sExpires = "; expires=" + vEnd;
break;
case Date:
sExpires = "; expires=" + vEnd.toUTCString();
break;
}
}
document.cookie = encodeURIComponent(sKey) + "=" + encodeURIComponent(sValue) + sExpires + (sDomain ? "; domain=" + sDomain : "") + (sPath ? "; path=" + sPath : "") + (bSecure ? "; secure" : "");
return true;
},
removeItem: function (sKey, sPath, sDomain) {
if (!sKey || !this.hasItem(sKey)) { return false; }
document.cookie = encodeURIComponent(sKey) + "=; expires=Thu, 01 Jan 1970 00:00:00 GMT" + ( sDomain ? "; domain=" + sDomain : "") + ( sPath ? "; path=" + sPath : "");
return true;
},
hasItem: function (sKey) {
return (new RegExp("(?:^|;\\s*)" + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=")).test(document.cookie);
},
keys: /* optional method: you can safely remove it! */ function () {
var aKeys = document.cookie.replace(/((?:^|\s*;)[^\=]+)(?=;|$)|^\s*|\s*(?:\=[^;]*)?(?:\1|$)/g, "").split(/\s*(?:\=[^;]*)?;\s*/);
for (var nIdx = 0; nIdx < aKeys.length; nIdx++) { aKeys[nIdx] = decodeURIComponent(aKeys[nIdx]); }
return aKeys;
}
};
and to set the cookie
docCookies.setItem("username",username,"Infinity");
and to get the cookie
docCookies.getItem("username") //returns the string
or
docCookies.has("username") //return boolean
I usually use below code for that:
function getCookie(cookieName) {
var i, x, y, cookiesArray = document.cookie.split(";");
for (i = 0; i < cookiesArray.length; i++) {
x = cookiesArray[i].substr(0, cookiesArray[i].indexOf("="));
y = cookiesArray[i].substr(cookiesArray[i].indexOf("=") + 1);
x = x.replace(/^\s+|\s+$/g, "");
if (x == cookieName) {
return unescape(y);
}
}
}
function checkCookie() {
hideCookieDiv();
var myCookie = getCookie("yourcookiename");
if (myCookie == null || myCookie != "true") {
showCookieDiv();
setCookie();
}
}
function hideCookieDiv() {
document.getElementById('YourDivId').style.display = "none";
}
function showCookieDiv() {
document.getElementById('YourDivId').style.display = "block";
}
function setCookie() {
var expirationDate = new Date();
expirationDate.setDate(expirationDate.getDate() + 365);
document.cookie = "yourcookiename=true; expires=" + expirationDate.toUTCString();
}

Insert a cookie to input value

I have a JavaScript function that stores the cookie value, and I want to insert it into a field in an HTML form (as in Facebook – having your e-mail prefilled after logging out).
The cookie originally is shown up with document.write.
I imagine I have to:
get the value of the VisitorName cookie
convert document.write to text
insert this text by changing input value through
document.getElementById('inputID').value = cookie value"
How can I do this? Here is the code:
var expDays = 30;
var exp = new Date();
exp.setTime(exp.getTime() + (expDays*24*60*60*1000));
function Who(info) {
var VisitorName = GetCookie('VisitorName')
if (VisitorName == null) {
VisitorName = "Dear visitor";
SetCookie ('VisitorName', VisitorName, exp);
}
return VisitorName;
}
function set() {
VisitorName = prompt("");
SetCookie ('VisitorName', VisitorName, exp);
}
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 SetCookie (name, value) {
var argv = SetCookie.arguments;
var argc = SetCookie.arguments.length;
var expires = (argc>2) ? argv[2] : null;
var path = (argc >3) ? argv[3] : null;
var domain = (argc >4) ? argv[4] : null;
var secure = (argc >5) ? argv[5] : false;
document.cookie = name + "=" + escape (value) +
((expires == null) ? "" : (";expires=" + expires.toGMTString())) +
((path == null) ? "" : (";path=" + path)) +
((domain == null) ? "" : (";domain=" + domain)) +
((secure == true) ? ";secure" : "");
}
function DeleteCookie (name) {
var exp = new Date();
exp.setTime (exp.getTime() - 1);
var cval = GetCookie (name);
document.cookie = name + "=" + cval + ";expires=" + exp.toGMTString();
}
document.write("" + Who() + ",")
Your post has already answered your own question. Putting the listings together:
<input id="visitor">
<script>
document.getElementById('visitor').value = GetCookie('VisitorName');
</script>
document.getElementById('inputID').value = GetCookie('VisitorName');

Categories