Cookie is being set.But document.cookie is null - javascript

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.

Related

How to set/change a cookie via php?

I use this code to change the cookie value in php, or set it if it does not exist yet:
setcookie('maintenance_site_contact_failed', '1', time()+3600, '/', 'entwicklung');
And I am using this code to set a cookie in javascript:
setCookie('maintenance_site_contact_failed', '0', 1);
function setCookie(name,value,days)
{
var expires = "";
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days*24*60*60*1000));
expires = "; expires=" + date.toUTCString();
}
document.cookie = name + "=" + (value || "") + expires + "; path=/";
}
But as you can see in the following screenshot the cookie is created a second time instead of changing the existing one, but the duplicate has a dot in the domain name.
Why is there a dot and why is the cookie created twice?
What I try:
If a user sends my form and the validation fails on serverside, then
I am setting the cookie maintenance_site_contact_failed in the PHP script to 1 so that the client knows that an error happened.
The javascript then checks the value of the cookie, and if the cookie value is 1 then it shows an error and resets the cookie value to 0.
Looks like your cookie is only available to different subdomains because in the php equivalent you're assigning a value for the domain parameter.
Try to do the same inside the Javascript setCookie function:
document.cookie = name + "=" + (value || "") + expires + "; path=/; domain=entwicklung";

Set a Javascript Cookie based on URL Params

I'm curious if someone can help a very new Javascript user make sense of how to set a cookie, based on specific URL parameters. I see that pulling the data from the URL using JavaScript is covered in this post:
How can I get query string values in JavaScript?
But I can not figure out how to pull that information into a cookie to store the information throughout a users session on the site.
I would like to grab 3 main URL parameters:
utm_source
utm_medium
utm_campaign
And then store them in a cookie in Google Tag Manager using Javascript.
I can not wrap my head around making this happen. Any help would be greatly appreciated. Sorry I dont have much code to show for reference, but I have been experimenting ( and failing ) for hours now.
Thank you so much for any insight on this.
Cheer,
Melissa
Edit:
Sorry...I wasn't expecting someone to write it for me, I just didn't think my very failed attempts would help anyone see what I was trying to do so I just explained.
Here is my code as of now, and I know it's sort of working. I'm editing a previous cookie that stores the site referrer in a cookie. So as it stands right now, the cookie stores the referrer on the first pageview, then if you go to a different page it will show the {{utm_medium}} and continue to show that throughout the visit. I would like for it to not show the referrer, but output a cookie that displays {{utm_source}} | {{utm_medium}} | {{utm_campaign}} if that's even possible...
Thank you again for any help or pointers or articles. I really appreciate it.
<script> //get referrer info and shorten it
var ref = {{Referrer}}
function extractDomain(url) {
var domain;
//find & remove protocol (http, ftp, etc.) and get domain
if (url.indexOf("://") > -1) {
domain = url.split('/')[2];
} else {
domain = url.split('/')[0];
}
//find & remove port number
domain = domain.split(':')[0];
return domain;
}
ref = extractDomain(ref);
//create cookie
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=/";
}
var cookie = "";
//check if UTMs are present and set cookie content to the source utm
if ({{utm_source}}) {
createCookie("utmsource", cookie + {{utm_source}}, 1000)
} else if ({{utm_medium}}) {
createCookie("utmsource", cookie + "Email", 1000)
//check if referrer is present and set cookie content to the referrer
} else if ({{utm_campaign}}) {
createCookie("utmsource", cookie + "{{utm_campaign}}", 1000)
} else if {
createCookie("utmsource", cookie + "Email", 1000)
};
</script>
When you use cookie + something, you're not updating the cookie string. So each time you do this, you're just concatenating with the original, empty value of this string. Instead of calling setcookie multiple times, update the cookie string as you test the different variables, then call setcookie at the end with the combined value.
You shouldn't use else if between each test, since that will only add the second variable to the cookie if the first variable didn't exist. But you want all the variables put into the cookie.
var cookie = "";
if ({{utm_source}}) {
cookie += {{utm_source}};
}
if ({{utm_medium}}) {
cookie += ' | ' + {{utm_medium}};
} else {
cookie += ' | Email';
}
if ({{utm_campaign}}) {
cookie += ' | ' + {{utm_campaign}};
} else {
cookie += ' | Email';
}
setcookie('utm_source', cookie, 1000);

Check returning visitors using cookies

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

Getting multiple cookie values for same cookie different paths

Working on a local url: http://127.0.0.1:8000/qa/
Setting cookies using this JS 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 + "=" + newSize + "; " + expires; + "path=/";
}
If I call setCookie from /qa/, I can see that the following cookie has been set:
Name=font; Value=12px; Domain=127.0.0.1; Path=/qa
If I subsequently call setCookie from a different url (eg /qa/profile), I see that a second cookie has been created as follows:
Name=font; Value=12px; Domain=127.0.0.1; Path=/qa
Name=font; Value=18px; Domain=127.0.0.1; Path=/qa/profile
What I want is for any call to setCoookie to override the previous value of the initial cookie so that there is only ever one cookie with name="font" and that its value always reflects the last set value. I thought that specifying "path=/"; in my jquery function would do the trick. But it hasn't. What am I doing wrong?

Delete all Google cookies from a Greasemonkey script [duplicate]

This question already has answers here:
Can a userscript delete cookies from a given domain?
(2 answers)
Closed 5 years ago.
I tried a lot of different scripts, but none worked. How do I delete the cookies created by Google, or all cookies of a site?
Best not to use Greasemonkey for this. It will be cumbersome, might miss cookies set long after the page loads, and can only delete Google cookies while you are actually browsing Google.
Plus, you have to set the script's // #include statements to catch all of Google's current and future domains (google.com, accounts.google.com, mail.google.com, google-analytics.com, etc.). And if Google serves "Secure cookies" those cannot be touched either.
Best to use a tool built for smartly deleting cookies. I recommend Selective Cookie Delete.
Also, Google, and other sites, track you with far more and worse than cookies. It's a good idea to run CCleaner at least once a week.
BUT, if you still want to do this with Greasemonkey, here is the code that will delete many cookies for the domain that the script is running on:
WARNING: JavaScript and Greasemonkey cannot even see all the cookies on a page, nor can "secure" (server only) cookies be deleted.).
//--- Loop through cookies and delete them.
var cookieList = document.cookie.split (/;\s*/);
for (var J = cookieList.length - 1; J >= 0; --J) {
var cookieName = cookieList[J].replace (/\s*(\w+)=.+$/, "$1");
eraseCookie (cookieName);
}
Where eraseCookie() is:
(Note that this eraseCookie gets many more cookies by attempting all possible paths and the most likely sub-domains.)
function eraseCookie (cookieName) {
//--- ONE-TIME INITS:
//--- Set possible domains. Omits some rare edge cases.?.
var domain = document.domain;
var domain2 = document.domain.replace (/^www\./, "");
var domain3 = document.domain.replace (/^(\w+\.)+?(\w+\.\w+)$/, "$2");;
//--- Get possible paths for the current page:
var pathNodes = location.pathname.split ("/").map ( function (pathWord) {
return '/' + pathWord;
} );
var cookPaths = [""].concat (pathNodes.map ( function (pathNode) {
if (this.pathStr) {
this.pathStr += pathNode;
}
else {
this.pathStr = "; path=";
return (this.pathStr + pathNode);
}
return (this.pathStr);
} ) );
( eraseCookie = function (cookieName) {
//--- For each path, attempt to delete the cookie.
cookPaths.forEach ( function (pathStr) {
//--- To delete a cookie, set its expiration date to a past value.
var diagStr = cookieName + "=" + pathStr + "; expires=Thu, 01-Jan-1970 00:00:01 GMT;";
document.cookie = diagStr;
document.cookie = cookieName + "=" + pathStr + "; domain=" + domain + "; expires=Thu, 01-Jan-1970 00:00:01 GMT;";
document.cookie = cookieName + "=" + pathStr + "; domain=" + domain2 + "; expires=Thu, 01-Jan-1970 00:00:01 GMT;";
document.cookie = cookieName + "=" + pathStr + "; domain=" + domain3 + "; expires=Thu, 01-Jan-1970 00:00:01 GMT;";
} );
} ) (cookieName);
}

Categories