Implementing own Client ID shows discrepancies compared to GA Client ID - javascript

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

Related

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.

create and save cookies on onclick

Can anyone help me set up a cookie function that can take user input by checking which link the user clicked on and then redirect them to that link and create a cookie for it so the next time the user comes they automatically get redirected.
Can anyone please tell me what am I doing wrong. I want multiple links and clicking on each link should create a cookie and redirect the user.
Can anyone provide a working jsFiddle please.
The code is below please help:
//Html
something site
something2 site
// Javascript
function redirectOne(state)
{
createCookie('state', state, 90);
window.location.href = "www.something1.com" + state;
}
function redirectTwo(state)
{
createCookie('state', state, 90);
window.location.href = "www.something2.com" + state;
}
var cookie = readCookie('state');
if (cookie != null)
{
window.location.href = "www.something.com" + 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=/";
}
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);
}
Your problem is that when you call this line in each function
createCookie('state', state, 90);
It's taking the value of '/home' from the onClick event and passing it to the cookie creation routine. You should be passing in something other than '/home' for both functions.
something site
something2 site
// Javascript
function redirectOne(state)
{
createCookie('state', state, 90);
window.location.href = state+'/home';
}
You do not need the redirectTwo function at all.

Cookie only working without the www in front of my domain

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

Javascript - Using cookies to store an integer

I am trying to use a cookie to store a single integer, so when the user refreshes the page I am able to retrieve the previous number they were on (in an attempt to stop doubles of a video appearing).
What would the minimum requirements be to accomplish this?
var randomNumber = Math.floor((Math.random()*10)+1);
document.cookie=(randomNumber);
Setting a cookie:
document.cookie = 'mycookie=' + randomNumber + ";max-age=" + (300) + ";";
Reading a cookie:
var cookie = document.cookie;
alert(decodeURIComponent(cookie));
The cookie contains some other random stuff like push=1 as well as mycookie. Should I be setting the cookie to null before I add the randomNumber?
As far as getting the value of mycookie would I just assign the cookie to a string and parse mycookie from it?
Tamil's comment is solid. Use these quirksmode functions if you ever wish to surpass minimal cookie usage:
cookie_create = function (name,value,days) {
var expires, date;
if (days) {
date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
expires = "; expires="+date.toGMTString();
}
else expires = "";
document.cookie = name+"="+value+expires+"; path=/";
expires = date = null;
};
cookie_read = function (name) {
var nameEQ = name + "=",
ca = document.cookie.split(';'),
len = ca.length,
i, c;
for(i = 0; i < len; ++i) {
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);
}
nameEQ = name = ca = i = c = len = null;
return null;
};
cookie_erase = function (name){
cookie_create(name,"",-1);
name = null;
};
You could use document.cookie to read/write cookies in javascript:
document.cookie = 'mycookie=' + randomNumber + '; path=/';
And if you wanted the cookie to be persistent even after the user closing his browser you could specify an expires date.

Cookie value to define style on page load

I am using the scripts from here http://www.quirksmode.org/js/cookies.html and have successfully created a cookie.. it is set based on the users response to the age drop down. However I am having trouble doing anything with it. I would like to have a style defined if a cookie is present. Here is the bulk of my scripts..
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;
}
function checkAge(){
var min_age = 13;
var year = parseInt(document.forms["emailForm"]["year"].value);
var month = parseInt(document.forms["emailForm"]["month"].value) - 1;
var day = parseInt(document.forms["emailForm"]["day"].value);
var theirDate = new Date((year + min_age), month, day);
var today = new Date;
if ( (today.getTime() - theirDate.getTime()) < 0) {
var el = document.getElementById('emailBox');
if(el){
el.className += el.className ? ' youngOne' : 'youngOne';
}
document.getElementById('emailBox').innerHTML = "<style type=\"text/css\">.formError {display:none}</style><p>Good Bye</p><p>You must be 13 years of age to sign up.</p>";
createCookie('age','not13',0)
return false;
}
else {
createCookie('age','over13',0)
return true;
};
};
window.onload=function(){
var x = readCookie('not13');
if (x) {
document.getElementById('emailBox').innerHTML = "<style type=\"text/css\">.formError {display:none}</style><p>Good Bye</p><p>You must be 13 years of age to sign up.</p>";
}
}
Age verification works and cookie is set.... no errors (from Firebug).. can anyone see what I am doing wrong?
with jQuery would be something like this
if (x) {
var style = "<style type=\"text/css\">.form {display:none}</style>";
$("header").append(style);
}
Looking at your code it should work. There's nothing incorrect about it.
The only thing I would suggest is that instead of injecting a style tag into a empty div, inject a link tag into the head. This will mean that your css changes and maintainance won't need to touch the js code.
I got it.. I was looking for the cookie value and needed to look for the name and then create an if statement based on the value. so..
var x = readCookie('age');
if (x=='not13') {
document.getElementById('emailBox').innerHTML = "<style type=\"text/css\">.formError {display:none}</style><p>Good Bye</p><p>You must be 13 years of age to sign up.</p>";
}

Categories

Resources