Universal Google Analytics Event Tracking Not Working - events

I have read all topics on the subject, and my code is still not tracking any events in the G Analytics. Please Help! Here goes the code:
The Analytics code:
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-XXXXXXX-1’, 'auto');
ga('require', 'displayfeatures');
ga('send', 'pageview');
</script>
The code in the button that opens a link in a new window:
Buy Tickets

If you copy and pasted the event tracking code directly from your site, then it may need some adjustment with the quotes. You should use the "straight" quotes (and I KNOW there's a name for them.... anyone?). The code should look like this with the fixed single and double quotes:
Buy Tickets
The same thing for the ga('create'..) line. Generally make all quotes straight.

Related

conditional statement that checks current url root directory (/en/ or /cn/ languages in this case)

My Magento website is bilingual (English default and Chinese), and has the Zopim livechat. Apparently, Zopim has language detection, but it didn't work for our website... I had a colleage use a Chinese computer with a Chinese IP and a Chinese browser visit the Chinese side of our website, and the Zopim live chat was STILL in English. So wtf?
I contacted the Zopim support team and they gave me some code to "put on all the Chinese pages." However, that's not how my website actually operates. I have a language plug-in/extension that translates certain words on the default-English webpages by replacing those words with their Chinese counterparts in .CSV translation docs on the server, but the phtml pages themselves are not technically Chinese. They are still the default pages which run the translation function, when the root is /ch/ instead of /en/
I thought maybe just putting it on the header.phtml block or the footer.phtml block might work, but actually those blocks are also just default blocks with the root-check-launches-translate feature built into it.
This is the code the Zopim support rep gave me:
<script type="text/javascript">
$zopim(function(){
$zopim.livechat.setLanguage('en');
$zopim.livechat.bubble.setText('Click here for livechat!’);
$zopim.livechat.badge.setText('test');
$zopim.livechat.window.setTitle('Zopim Chat Support');
$zopim.livechat.concierge.setTitle('Zopim Chat Support');
$zopim.livechat.setGreetings({
'online': ['online short message', 'online long message'],
'offline': ['offline short message', 'offline long message']
});
});
</script>
So, can a simple conditional [IF] statement be added to the top of this that can check if the root is /ch/... [THEN] apply all the following code? Also, am I allowed to put that on the footer or header (which appear on all pages), or do I have to do add it to index.html (which for some reason I can't even find in the server)?
Try placing this piece of code in the file (footer.phtml) of your current theme:
<?php if (strpos(Mage::app()->getLocale()->getLocaleCode(), 'zh_') !== false): ?>
<script type="text/javascript">
$zopim(function(){
$zopim.livechat.setLanguage('en');
$zopim.livechat.bubble.setText('Click here for livechat!’);
$zopim.livechat.badge.setText('test');
$zopim.livechat.window.setTitle('Zopim Chat Support');
$zopim.livechat.concierge.setTitle('Zopim Chat Support');
$zopim.livechat.setGreetings({
'online': ['online short message', 'online long message'],
'offline': ['offline short message', 'offline long message']
});
});
</script>
<?php endif; ?>

Tracking events in Universal Analytics only partly working

Currently using Universal Analytics on my website that's already tracking PDF downloads and I'm trying to implement this for a video as well, to see how many times this video has been played.
<p><iframe width="482" height="271" src="video URL" scrolling="no" frameborder="0" allowfullscreen="" onClick="ga('send', 'event', 'videos', 'play', 'eco-assistant', '10');"></iframe></p>
This is the actual page.
Any idea why video plays are not tracked?
Many thanks,
B.
Another thing to keep in mind is that the value attributed to the event should be an integer, not a string. Your onClick code should be the following:
onClick="ga('send', 'event', 'videos', 'play', 'eco-assistant', 10);"
Hope this additional information is helpful.
B. Keller

Is there a way to setup Clicktale tag in Google Tag Manager?

Since GTM doesn't support document.write() method the standard clicktale code doesn't work. Is there a workaround for this?
ClickTale employee has sent me these instructions:
Replace the document.write JS line above with the following:
document.body.appendChild(externalScript);
Example:
<!-- ClickTale Bottom part -->
<script type='text/javascript'>
var externalScript = document.createElement('script');
var scrSrc = document.location.protocol=='https:'?
'https://clicktalecdn.sslcs.cdngc.net/':
'http://cdn.clicktale.net/';
scrSrc += 'www11/ptc/xxx-xxx-xxx-xxx.js';
externalScript.src = scrSrc;
externalScript.type = 'text/javascript';
document.body.appendChild(externalScript);
</script>
<!-- ClickTale end of Bottom part -->
I am not sure what to do with this. Has someone tried something like this?
The correct way to do it is explained in http://wiki.clicktale.com/Article/Google_Tag_Manager_Integration
The procdeure is:
Create a new container (or add the below to an existing container).
Create a new Custom HTML tag in your GTM container.
Copy and paste your project’s bottom code (from the ClickTale account) into the new
tag.
Check the “Support document.write” checkbox.
I tried it and it worked. Anyway I had to wait 24h (probably it's the time that Google needs for publishing the tag).
The above answer will work, but Google Tag Manager does have a template for ClickTale now, I always try to refrain from using the Custom HTML tag because this can absolutely break your site if done incorrectly
To set up ClickTale within GTM
New - Tag
Certified Analytics
ClickTale Standard Tracking.

Events not being tracked in new Google Analytics (analytics.js) setup

I have a website that I am using the new Universal Analytics (analytics.js) to track. Everything is setup and working (pageviews, referrals, etc.) using the following code snippet:
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-39570713-1', 'site.com');
ga('send', 'pageview');
</script>
That is located before the </head> tag.
I am using JQuery to fire off an event. I tested the JQuery with an alert message and it is getting called, so that isn't the problem. Here is the snippet that fires when a button is clicked:
$('#submitButton').on('click', function() {
ga('send', 'event', 'button', 'click', 'contact form');
});
Nothing is appearing in the Events section of Analytics. I keep clicking the button, even from different computers just to make sure it isn't excluding my IP address. Because the Analytics doc that Google provides does not provide a whole lot of explanation I'm at a loss here.
If you are using Google Tag Manager and also want to trigger some events via code, ga('send'...) does not appear to be enough. You need to first fetch the appropriate analytics object:
if ("ga" in window) {
tracker = ga.getAll()[0];
if (tracker)
tracker.send("event", "Test", "Test GA");
}
Note that this assumes you're only using a single Google Analytics Tracking code on your site. If you happen to be using multiple, you may need to fetch the appropriate one by name or index.
New version of analytics has a new syntax. Replace the line below;
ga('send', 'event', 'button', 'click', 'contact form');
with this;
gtag('event', 'click', {'event_category' : 'button',
'event_label' : 'contact form'});
Reference;
https://developers.google.com/analytics/devguides/collection/gtagjs/events
For testing purposes you could also use the hitCallback method:
ga('send', {
'hitType': 'event',
'eventCategory': 'button',
'eventAction': 'click',
'eventLabel': 'contact form',
'hitCallback' : function () {
alert("Event received");
}
});
Update: comma was missing.
For GA for this moment...
Sending a new page in SPA looks finally like this for me:
if (window.ga){
window.ga.getAll()[0].set('page', location);
window.ga.getAll()[0].send('pageview')
}
This shows exactly what wanted on GA reports like a new page is hit and the title and all are correct.
In my case the problem was uBlock Origin that was blocking the analytics script from loading.
I had the exact same problem. I had to create a new property and select "Universal Analytics" instead of "Classic Analytics" (it is labeled as "beta"). Now events are captured properly.
I had this same problem, and I think I've found the solution, but it really leaves a bad taste in my mouth about Universal Analytics.
What I had to do was explicitly use the synchronous analytics API. So instead of including the usual snippet in your <head> tag, use the following code:
<script src="//www.google-analytics.com/analytics.js"></script>
<script>
tracker = ga.create('UA-XXXXXXX-1', 'example.com');
tracker.send('pageview');
</script>
Then you call the event tracking code like this:
tracker.send('event', 'Category', 'Action', 'Label');
This will ensure that the tracking beacon is sent to Google and acknowledged before the page the user navigated to starts loading.
This suggests that Universal Analytics requires some kind of additional acknowledgment beyond what the old ga.js analytics code required. So when you attach an event to a click that brings the user to another page, that acknowledgement can't be sent because the browser has left the page and dropped the current javascript execution stack.
Maybe this problem is specific to certain execution environments (I'm using Chrome 34 on OSX Mountain Lion), which might explain why more developers aren't noticing this problem.
today I needed to setup analythics for the first time and I found myself in the same trouble.
I found that the bast way to deal with the multiple trackers to avoid the getAll(), is this:
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-xxxxxx-y', 'auto', 'tracker');
ga('tracker.send', 'pageview');
ga('tracker.send', 'event', 'test', 'click', 'automaticEvent')
Note that you have to pass a "name" to the create method, and then you send an event to that tracker with ga([trackerName].send, ...)
Reference: https://developers.google.com/analytics/devguides/collection/analyticsjs/accessing-trackers
If anyone is trying to send an event to Google Analytics and wondering why the send function is doing nothing without any clear hint, I recommend using the debug version of their library. It will log some useful hints in the browser console.
Instead of getting the script from https://www.google-analytics.com/analytics.js, get it from https://www.google-analytics.com/analytics_debug.js. I found this out from their documentation.
I cannot see anything wrong with the code itself. Have you tried using the alternative event tracking?
ga('send', {
'hitType': 'event', // Required.
'eventCategory': 'button', // Required.
'eventAction': 'click', // Required.
'eventLabel': 'contact form'
});
I would also suggest testing the website with GA Debug Chrome addon, which allows you to see the tracking beacon was sent or not.
"Official" debugging documentation for Universal Analytics is still missing as of now, but hopefully it will be added soon as ga_debug.js provides lot of useful ways how to find out what's wrong with Analytics implementation...
I have the same problem, and it looks like events are tracked, but GA dashboard doesn't allow to browse them. This is the only way how I could interprete the "Visits with events: 1071" but "Total events: 0" that GA dashboard shows me.
UPD: With GA Chrome debug, have found a problem; 1st method is not working (sends the event without any data attached), but the 2nd one is OK.
You should also consider that it is likely that the page gets reloaded after the submit event was fired before the ga script was able to execute the 'send' method. To avoid this you could employ the 'hitCallback' mechanism, i.e. prevent the submit, call the ga send-method and submit the form data in the callback.
I got it working - my example is using the new Universal Analytics.
<script type="text/javascript">
function sliderOnChange() {
var period = window.convertDays(($("#PeriodSlider").slider("value")));
var amount_of_credit = $("#AmountOfCreditSlider").slider("value");
var gaEventInput = "£" + amount_of_credit + " for " + period;
ga('send', 'event', 'slider', 'sliding', gaEventInput);
}
</script>
Make sure Google Analytics / Google Tag Manager filters are not excluding any traffic from different domain. (Maybe you are testing it to get this working using different domain)
Recheck your GA id and domain in ga('create', 'UA-39570713-1', 'site.com');
Create a new profile in Google Analytics (GA) for testing purposes and debug your html in the same domain you define in GA.
Change the date to be today in GA - you might also need to wait some time before it appears in GA
I recommend sending GTM event via window.dataLayer.push({ event: 'EVENT_NAME', ...data }) and in GTM creating a trigger to fire a tag which sends event to Google Analytics. You'll have the best debugging experience with GTM preview and you'll be sure that events will be sent from GTM to GA, because GTM takes care of that.
onclick ga() function not working for me, I have also added the 'analytics.js' in <head> section -
<a mat-list-item routerLink='/dashboard' onclick="ga('send', 'event', 'Dashboard', 'Click', 'demoClick, 30);">
<mat-icon color="accent">home</mat-icon>
<span class="side-item">Dashboard</span>
</a>
gtag() function working fine for me, only the 'gtag.js' added in <head> section, 'analytics.js' not required or can be removed -
<a mat-list-item routerLink='/dashboard' id="sideNavDashboard" onclick="gtag('event', 'Click', {'event_category':'Dashboard', 'event_label':'demoClick', 'value':'30'});">
<mat-icon color="accent">home</mat-icon>
<span class="side-item">Dashboard</span>
</a>
Result (Google Analytics output) -
I was seeing everything except Events (both real-time and report). My steps included:
Calling Google and they found out that my GTM tag for Google Optimize was stopping all events to be sent to Analytics.
Removed the Optimize tag from Google tag manager and events started popping up in Analytics.
Try pausing some tag if you have this issue. Also connect the event tag to some goal.
I am using Vue.js and it seems I have to create ga each time, even though it was already created on the window:
ga('create', yourGtagId, 'auto');
ga('send', {});
In my case it didn't work because I loaded the HTML file directly from the file system.
Loading the page via a web server did the trick.
For local development a tool like https://github.com/tj/serve does a great job.
The only way I solved the problem was rolling back to the previous version of Analytics (non-beta):
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-39570713-2']);
_gaq.push(['_setDomainName', 'optimino.com']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
You can also use a jquery plugin I wrote for the new Universal Analytics:
https://github.com/pascalvgemert/jquery-analytics-event-tracking

Partially block embedded JavaScript in Firefox

Is there a Firefox extension capable of blocking a single function from embedded javascript in a page?
<html>
<head>
<script type='text/javascript'>
function onLoad(){
setTimeout(annoying, 1800000);
}
function annoying(){
//do something annoying
}
function useful(){
//do something useful
}
</script>
</HEAD>
<BODY onload="onLoad()">
<!--rest of page goes here-->
</BODY>
</HTML>
Perhaps Greasemonkey is the way to go.
The answer below is quite detailed technical, sorry if I went too far ;)
It depends a bit on how the function annoying() is used by the scripts. I am not yet an expert in JavaScript, some more experienced person's voice could be useful.
If annoying() is used by functions like window.setInterval(), window.setTimeout(), you probably can't overwrite the function directly, because of JavaScript quirks with scoping (closures). When the code window.setTimeout(annoying, 600) is executed, a reference to the "old" annoying is stored and that "old" version is executed. You might then try to get rid of the code that is invoking window.setTimeout on annoying instead.
In other cases, you can add a function with the same name and de facto overwrite the function with the following Greasemonkey userscript:
function addScript(sourceCode)
{
var script = document.createElement('script');
script.innerHTML = sourceCode;
var head = document.getElementsByTagName("head")[0];
head.insertBefore(script, head.firstChild); // insert the script as a first child of <HEAD>
}
addScript('function annoying(){alert("overwritten")}');
If you have code like below (I am unable to provide live demo, because it works differently on JSFiddle perhaps because its sandboxing), and the userscript above is launched for that domain, then after 600 milliseconds after page loads, you will have "Nasty alert" alert, but then any time you click the text, you will have "overwritten" alert.
<html>
<head>
<script type='text/javascript'>
function annoying(){
alert("Nasty alert");
}
function useful(){
//do something useful
}
window.setTimeout(annoying, 600); // closure; binds to the function as it is at the moment of execution
</script>
</head>
<body>
<a onclick="annoying()">Click me</a>
</body>
</html>
I know how to block it per page... I have a script here that is bugging me:
<script type="text/JavaScript">
<!--
function timedRefresh(timeoutPeriod) {
setTimeout("location.reload(true);",timeoutPeriod);
}
// -->
</script>
</head>
<body onload="JavaScript:timedRefresh(300000);">
What these idiots refuse to consider is that if I'm looking around for solutions, I could wind up with 10+ of these page open and 90% of my CPU time is then dedicated to refreshing their pages in the background! grr
I have firebug handy for web development and I just enter this JS command into the console
timedRefresh = function(value){alert(value);}
smile, click ok, and go on my way.
I've posted a solution here: https://stackoverflow.com/a/9699686/6355
Since it's little more than a link here it goes again: http://userscripts.org/scripts/show/125936
This does not help but instead exacerbates the problem.
The following are particularly pernicious and ugly if javascript is enabled:
<script>
setInterval("alert('irritate')",10)
</script>
or
<script>
(function(){(function r(){alert('irritate');setTimeout(r,10)})()})()
</script>
though this can be stopped (and all future TimeOuts) by:
javascript:setTimeout=function(){}
perhaps as the URI of a bookmark, provided it can be clicked fast enough.
However,
setInterval("alert('irritate')",10)
can only be stopped by
javascript:setInterval=function(){}
BEFORE the script is run.
Good luck with:
<script>
(function(){(function r(){alert('irritate');r()})()})()
</script>
or even simpler
<script>
( function r(){alert('irritate');r()} ) ()
</script>
Setting alert=function(){} will stop all messages but the script and its recursion of r will not stop until SO or system time out. Also, r is not in the global environment so r=function(){} is ineffective.
Some FF versions need an interesting solution, found on SO, if the alert response is mandatory, to kill the annoying page w/o killing the browser and other open tabs, by using ctrl-F4 to close the tab of the offending page. To aid the manual reflex and dexterity required to do this fast enough, ctrl-Enter is used to respond to the prompt and while ctrl-Enter is pressed F4 is typed.

Resources