Cookie only working without the www in front of my domain - javascript

I am setting a cookie in a disclaimer php file like this...
<script language = "JavaScript">
<!-- Begin hiding
function getCookieExpireDate(noDays){
var today = new Date()
var expr = new Date(today.getTime()+noDays*24*60*60*1000*365)
return expr.toGMTString()
}
function makeCookie(name, data, noDays){
var cookieStr = name + "="+ data
if (makeCookie.arguments.length > 2){
cookieStr += "; expires=" + getCookieExpireDate(noDays)
}
document.cookie = cookieStr
var hello="agreedterms.html";
window.location=hello;
}
function noway(){
var goodbye="index.html";
window.location=goodbye;
}
// End hiding -->
</script>
And then checking for it in index php like this....
<script language = "JavaScript">
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 (cookieName) {
var arg = cookieName + "=";
var argLength = arg.length;
var cookieLength = document.cookie.length;
var i = 0;
while (i < cookieLength) {
var j = i + argLength;
if (document.cookie.substring(i, j) == arg) {
return getCookieVal(j)
}
if (i == 0) {
break
}
}
return null;
}
if(getCookie('disclaimer') == null) {
location.href="disclaimer.php"
}
</script>
This all works fine if I access the site using mydomain.com - but if I use www.mydomain.com then it doesn't work.
Any ideas what I am doing wrong? Do I need to include the www somehow?

If I remeber you have to set the domain and path for the cookie by appending following to your cookie string
;domain=.domain.com;path=/
Where obviously you replace the domain by your domain. The . in front of the domain name makes it valid for all subdomains following the domain you are currently on.
Edit:
See also the following Stack Overflow answer: Creating a javascript cookie on a domain and reading it across sub domains

Related

Document.cookie configure CookieJar for domain localhost

I am using a getCookie function to access cookies in a Pinia store. When trying to test this with Vitest, I get the following error:
Error: Cookie has domain set to the public suffix "localhost" which is a special use domain. To allow this, configure your CookieJar with {allowSpecialUseDomain:true, rejectPublicSuffixes: false}.
Below is the code for the getCookie function I am using:
//https://stackoverflow.com/a/5968306/14131782
function getCookie(name: string) {
var dc = document.cookie;
var prefix = name + "=";
var begin = dc.indexOf("; " + prefix);
var end = 0;
if (begin == -1) {
begin = dc.indexOf(prefix);
if (begin != 0) return null;
} else {
begin += 2;
end = document.cookie.indexOf(";", begin);
if (end == -1) {
end = dc.length;
}
}
return decodeURI(dc.substring(begin + prefix.length, end));
}
Is there some way I can configure document.cookie for testing this?
This was resolved by updating the tough-cookie module

Cookies on external server

I'm using the code below to handle cookies, it works fine locally, but when I upload it to our testserver the cookies are not set (it's the same for Firefox, IE and Chrome, so I don't think it's a browser issue).
Cookies are allowed since I can set cookies using PHP setcookie("RFT_reeftWpLang", $lang, time()+29030400, dirname($_SERVER["SCRIPT_NAME"]), $_SERVER["SERVER_NAME"]);
Neither locally nor on the server I get any errors when I try to set document.cookie, but on the server console.log( getFilterCookie(cname)); return an empty string where I do get the expected value locally.
I know you probably can not say what's wrong without access to the server, but I hope you might tell me what to look for in order to pinpoint the error
function setFilterCookie(cname,cvalue,exdays) {
var cookiePath = "/";
var pathArray = window.location.pathname.split( '/' );
if (pathArray.length > 2 && $.trim(pathArray[1]) != "" ) {
cookiePath = cookiePath+pathArray[1];
}
var d = new Date();
d.setTime(d.getTime()+(exdays*24*60*60*1000));
var expires = "expires="+d.toGMTString();
try {
document.cookie = cname+"="+cvalue+"; "+expires+"; domain="+window.location.host+"; path="+cookiePath ;
} catch (e) {console.log(e);}
if(exdays < 0) {
document.cookie = cname+"="+cvalue+"; "+expires;
}
console.log( getFilterCookie(cname));
}
function getFilterCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++) {
var c = $.trim(ca[i]);
if (c.indexOf(name)==0) {
return c.substring(name.length,c.length);
}
}
return "";
}
function delFilterCookie(cname) {
setFilterCookie(cname, "", -1);
}
Thank for helping
On our testserver we have the port in the url, so it get's part of the domain, it works's after I have changed my code to
var domainArray = window.location.host.split( ':' );
var domain = domainArray[0];
try {
console.log(document.cookie = cname+"="+cvalue+"; "+expires+"; domain="+domain+"; path="+cookiePath);
} catch (e) {
console.log(e);
console.log("fail setFilterCookie" + cname + " - " + cvalue + " - " + exdays);}

JavaScript Compiler Error in Tag Manager

I'm trying to use a cookie to set user pageviews per session through GTM. I'm using a custom JavaScript variable:
function readCookie(name) {
var cookieName = name + "=";
var cookieSplit = document.cookie.split(';');
for (var i = 0; i < cookieSplit.length; i++) {
var cookies = cookieSplit[i];
while (cookies.charAt(0) === ' ') cookies = cookies.substring(1, cookies.length);
if (cookies.indexOf(cookieName) === 0) return cookies.substring(cookieName.length, cookies.length);
}
return null;
}
function viewAppend() {
var oldCookie = readCookie('viewCount');
if (oldCookie === null) {
document.cookie = "viewCount=1; path=/";
} else {
var views = oldCookie + 1;
document.cookie = "viewCount="+views+"; path=/";
}
}
viewAppend();
I keep getting the same Compiler error: "Error at line 12, character 1: Parse error. ')' expected."
I can't seem to figure out what I'm doing wrong, but any help is appreciated.
------ EDIT ------
Via my comment below, this is my current code. Current error is : "Error at line 16, character 40: Parse error. Semi-colon expected"
function doStuff() {
function readCookie(name) {
var cookieName = name + "=";
var cookieSplit = document.cookie.split(';');
for(var i=0;i < cookieSplit.length;i++) {
var cookies = cookieSplit[i];
while (cookies.charAt(0) === ' ') cookies = cookies.substring(1,cookies.length);
if (cookies.indexOf(cookieName) === 0) return cookies.substring(cookieName.length,cookies.length);
}
return null;
}
function viewAppend() {
var oldCookie = readCookie('viewCount');
if (oldCookie === null) {
document.cookie = "viewCount="1"; path=/";
} else {
var views = parseInt(oldCookie) + 1;
document.cookie = "viewCount="+views+"; path=/";
}
}
}
You have quoting problems on this line:
document.cookie = "viewCount="1"; path=/";
it should be:
document.cookie = "viewCount=1; path=/";
You don't need to put quotes around the value of a cookie (and if you did, you could either escape them or use single quotes around the whole string).
Alright, I went back to the drawing board and tried approaching the problem another way. At first I was trying to build everything into a single custom JavaScript variable in GTM. That was folly. I decided to approach it as such:
First, I built a custom HTML tag in GTM to read/write the PageView cookie that fired on all pages.
<script>
function readCookie(name) {
var cookieName = name + "=";
var cookieSplit = document.cookie.split(';');
for(var i=0;i < cookieSplit.length;i++) {
var cookies = cookieSplit[i];
while (cookies.charAt(0) === ' ') cookies = cookies.substring(1,cookies.length);
if (cookies.indexOf(cookieName) === 0) return cookies.substring(cookieName.length,cookies.length);
}
return null;
}
function viewAppend() {
var oldCookie = readCookie('viewCount');
if (oldCookie === null) {
document.cookie = "viewCount=1; path=/";
} else {
var views = parseInt(oldCookie) + 1;
document.cookie = "viewCount="+views+"; path=/";
}
}
viewAppend();
</script>
Then I built a custom Javascript variable that read the cookie and returned it as an integer.
function doStuff() {
function readCookie(name) {
var cookieName = name + "=";
var cookieSplit = document.cookie.split(';');
for(var i=0;i < cookieSplit.length;i++) {
var cookies = cookieSplit[i];
while (cookies.charAt(0) === ' ') cookies = cookies.substring(1,cookies.length);
if (cookies.indexOf(cookieName) === 0) return cookies.substring(cookieName.length,cookies.length);
}
return null;
}
var oldCookie = readCookie('viewCount');
var views = parseInt(oldCookie);
return views;
}
Then I simply built my pagievew tag that triggered whenever the pageviews variable was greater than 4 on Window Load to indicate an engaged user.
Thanks #Barmar for the help thinking about the problem. Your questions definitely challenged how I was approaching it.

Implementing own Client ID shows discrepancies compared to GA Client ID

I want to implement my own Test-Client ID with the following Skript:
<script>
(function(){
var cookie = readCookie("customClientID");
var storage = window.localStorage;
var storageClientID = storage.getItem("customClientID"");
var userID = userId();
var agent = window.navigator.userAgent;
if(!cookie && !storageClientID){
createCookie("customClientID"", userID, 2);
storage.setItem("customClientID"", readCookie("customClientID""));
}else if(cookie && !storageClientID){
storage.setItem("customClientID"", readCookie("customClientID""));
}else if(!cookie && storageClientID){
createCookie("customClientID"", storageUserId, 2);
}else{}
//Create UUID
function userId() {
try{
return new Date().getTime() + '.' + Math.random().toString(36).substring(5) + '.' + hash(agent);
}catch(e){}
}
//Hash Function
function hash(str){
try{
var hash = 0;
for(var i = 0; i < str.length; i++){
var charI = str.charCodeAt(i);
hash = ((hash<<5)-hash)+charI;
hash = hash & hash; // Convert to 32bit integer
}
hash = hash & hash;
hash = hash.toString().replace("-", "");
return hash;
}catch(e){}
}
//Read Cookie https://www.quirksmode.org/
function readCookie(name) {
try{
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;
}catch(e){}
}
//Create Cookie https://www.quirksmode.org/
function createCookie(name,value,days) {
try{
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=/";
}catch(e){}
}
})();
The if block checks if the cookie is set and the cookie value also appears in the local storage. If the cookie is not found a new cookie is set with a value generated function userId().
To get the customClientID value out of the cookie I use the internal GTM First Party Cookie variable. The custom HTML tag with the script above fires on All Pages - Pageview.
Finally I've set a Custom Dimension (User Scope) with the First Party Cookie variable (customClientID) value in each tag.
When I compare the Users Metric of the original GA ClientID I get 1 User for each ClientID which is correct. However, if I compare the customClientID in a custom report with the same date range e.g. one day I get a lot of Users with the same customClientID. There are also less Users in sum compared to the original ClientID.
We have a high traffic website so my first assumption is that the script is maybe to slow to handle a lot of users entering and browsing at the same time. Many users would get the same customClientID.
Second assumption is that the custom dimension should only set within the page view tag.
Hope you understand my issue and many thanks in advance!
PS: I posted it here https://productforums.google.com/forum/#!topic/tag-manager/syet129zIqI;context-place=forum/tag-manager as well.
Best,
Anton

hiding div javascript (vanilla) cookie

I'm trying to hide a div with javascript and store that information for the rest of the session. Closing the div isnt a problem but somehow the information isnt stored in my cookie.. this is what i have so far.
var p = document.getElementById ('pcontainer');
window.onload = function () {
if(document.cookie.length != 0){
var nameValueArray = document.cookie.split("=");
p.style.display = nameValueArray[1];
}
}
function popup(){
if(p.style.display != 'none'){
var none = 'none';
p.style.display = none;
document.cookie = "geenpopup=" + none;}
}
To set a cookie, you can use document.cookie = "name=value";, but to retrieve a cookie, you should do something like splitting the cookie by semi-colons, then find your variable name in the array of values. Something like this function:
function getCookie (name) {
var cookieValue = null;
if (document.cookie && document.cookie !== '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = cookies[i].trim();
if (cookie.substring(0, name.length + 1) == (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
This function copied (and translated to vanilla JS) from Django docs.
So in your case, you could get the value with getCookie('geenpopup') [sic];

Categories

Resources