Tracking external links with Google Analytics trackPageview() not working - google-analytics

I have set up external link tracking as Goals in Google Analytics according to the GA documentation.
Here is the page in question: http://playmoreatthey.org/ - the external links on the page are formatted such as
Bayside Family YMCA
I set up the goal as a "head match" to the URL: /G1/bayside_family.com
I checked back four days later, and there are no results in the goals or pageviews for the phony "pagename" (/G1/bayside_family.com) specified in the JavaScript attached to each external link.

Looks like on your page you are using GA's async style code _gaq.push(...) but in your onclick you are using their old, "traditional" style code. You need to use
onclick="_gaq.push(['_trackPageview','/G1/bayside_family.com']);"

If you are using jQuery you can automatically track all the links on your site using this script:
// Outbound Link Tracking with Google Analytics
// Requires jQuery 1.7 or higher (use .live if using a lower version)
$("a").on('click', function(e){
var url = $(this).attr("href");
if($.trim(url).indexOf("javascript:") == 0) return;
if (e.currentTarget.host != window.location.host) {
_gaq.push(['_trackEvent', 'Outbound Links', e.currentTarget.host, url, 0]);
var target = $(this).attr("target");
if (e.metaKey || e.ctrlKey || target == "_blank") {
var newtab = true;
}
if (!newtab) {
e.preventDefault();
if(target) {
setTimeout('window.open("' + url + '", "' + target + '");', 100);
} else {
setTimeout('document.location = "' + url + '"', 100);
}
}
}
});
I found the script here: http://wptheming.com/2012/01/tracking-outbound-links-with-google-analytics/comment-page-1/#comment-39716
At the site you can find a debug version that will let you confirm that the script is working correctly.
I deviated from the original script by adding support for links with javascript (aka href="javascript:..."). Also I added code to honor the target attribute.
Here is a jsFiddle so you can see the script in action: http://jsfiddle.net/luisperezphd/45NPe/

One recommended way of doing this is through Events. That way your pageviews metric will not be inflated by the virtual pageviews tracked using the _trackPageview method.
http://support.google.com/analytics/bin/answer.py?hl=en&answer=1136920
I add this as an answer because Crayon Violent's comment above contains a broken link. At least someone will be able to edit this answer if the link needs to change again in the future.

Related

Autofill an external form in an iframe from... another form

I'd like to point your kind attentions to my question, topic should be similar to this post.
In a WP website i have two columns:
Column n.1 There is a CF7 form that is autofilled by an url from a CRM and injects data to a GSheet.
Column n.2 There is an iframe for booking an appointment with an external calendar tool that should pick data from the form (i have no way to edit form, but just the iframe link, for example:
Is there the possibility for this link to "pick" the data from the form or also from the crm url? Do you think that is possible or am I a fool?
Many thanks for your help :)
You should look into using JavaScripts postMessage() functionality to pass data to/from iFrames.
https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage
Use something like this on the WordPress page
// This will get the value of the input and send it to the iFrame on the fly
$('#form-id input:not([type=submit])').each(function() {
var val = $(this).val();
$(window).postMessage(val);
});
Then on the iFrame page:
// Create browser compatible event handler.
var eventMethod = window.addEventListener ? "addEventListener" : "attachEvent";
var eventer = window[eventMethod];
var messageEvent = eventMethod == "attachEvent" ? "onmessage" : "message";
// Listen for a message from the WP page
eventer(messageEvent, function(e) {
if (e.data.length < 1) return;
// jQuery
$('#input-id').val(e.data);
// Pure JS
document.getElementById('input-id').setAttribute('value', e.data);
}, false);
If the forms on different domains I think this is the only method for doing this.

How can I tell if my Google content experiment is running?

I've created a google content experiment without redirects using the docs.
The basic implementation involves a javascript snippet that uses the following code to choose the version of the experiment:
<!-- Load the Content Experiment JavaScript API client for the experiment -->
<script src="//www.google-analytics.com/cx/api.js?experiment=YOUR_EXPERIMENT_ID"></script>
<script>
// Ask Google Analytics which variation to show the user.
var chosenVariation = cxApi.chooseVariation();
</script>
<!-- Load the JQuery library -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script>
// Define JavaScript for each page variation of this experiment.
var pageVariations = [
function() {}, // Original: Do nothing. This will render the default HTML.
function() { // Variation 1: Banner Image
document.getElementById('banner').src = 'bay-bridge.jpg';
},
function() { // Variation 2: Sub-heading Text
document.getElementById('heading').innerHTML = 'Look, a Bridge!';
},
function() { // Variation 3: Button Text
document.getElementById('button').innerHTML = 'Learn more';
},
function() { // Variation 4: Button Color
document.getElementById('button').className = 'button button-blue';
}
];
// Wait for the DOM to load, then execute the view for the chosen variation.
$(document).ready(
// Execute the chosen view
pageVariations[chosenVariation]
);
</script>
However, when I visit the page using an incognito window, I only see the first variation of the experiment. When I check chosenVariation in the console, it's always 0. In fact, when I call cxApi.chooseVariation(); in the console, it always returns 0.
Is this because google recognizes my incognito browser windows, or is something broken with cxApi.chooseVariation(); or in my implementation?
I had the same problem, 100% of the sessions were given the original (0) variation. In order to fix the problem, I added the javascript code provided by the experiment. Go to your experiment (edit), click Setting up your experiment code, manually insert the code, copy the code in there.
Now since you (and I) don't want to have a redirect, remove this part at the end of the code <script>utmx('url','A/B');</script>. If your page is templated, you can use a variable and insert your experiment key (not experiment id) where you see var k='########-#'
Now either very few people use the experiments in a client-only fashion or we're totally stupid because it would seem to me that the guide is wrong and there's absolutely no documentation that shows a working client-only setup.

Google Analytics Experiments without redirect: maldistribution of sessions

Sorry for my English.
I have created new experiment in Google Analytics, and have used method without redirects. And i created tag in Google Tag Manager with this content
#script with api
<script src="//www.google-analytics.com/cx/api.js?experiment=1EN3yB34T0WE-0WxSqvsKw"></script>
<script>
# item ids to launch test
var itemIds= ['898324', '914734', '904249', '936082', '904275', '951077', '977818', '942227', '933907'];
if( $.inArray({{productId}}, itemIds) !== -1 ) {
# get chosed variation
var chosenVariation = cxApi.chooseVariation();
$(function(){
if (chosenVariation == 1) {
$('div.orange.service').hide();
$('div.orange.cardif').hide();
}
});
# make non-interaction hit to send data. Maybe here i get mistake
#(hit making by send data to Google Tag Manager, and all events with event === OWOX - will send to Google Analytics)
dataLayer.push({"event":"OWOX","eventCategory":"Non-Interactions","eventAction":"show","eventLabel":"products","products":[]});
}
</script>
And after 7 days of experiment we have:
big gap between original variant and variant with alternative design
And i want to ask why the gap between original page and page with alternatibe design so big?

Use Google Analytics (Asynchronous version) to track outgoing clicks without breaking target=_blank

I want to track users clicking links to external sites. I'm happy to use the asynchronous version of GA as this allows (in most browsers) the page to continue loading instead of halting at the script tag and waiting for google-analytics.com/ga.js to download and execute.
Google recommends this function:
<script type="text/javascript">
function recordOutboundLink(link, category, action) {
try {
var myTracker=_gat._getTrackerByName();
_gaq.push(['myTracker._trackEvent', ' + category + ', ' + action + ']);
setTimeout('document.location = "' + link.href + '"', 100)
}catch(err){}
}
</script>
<a href="http://www.example.com" onClick="recordOutboundLink(this, 'Outbound Links', 'example.com');return false;">
The problems with this solution:
It could take 10ms, it could take 300ms for the event to be tracked, but it'll change the page after 100ms no matter what happens. And if the tracking is too slow the page will change before it's been tracked.
document.location = means the original link is ignored and therefore target=_blank does not open new tabs/windows.
Possible solutions:
Busy wait (do {curDate=new Date();} while(curDate-date<millis)) for 100ms while the tracking has a chance to send it's request off then return true. Bad because busy waiting consumes all CPU available.
Use window.open so that new tabs/windows can be opened, which leads me to my current favourite:
In the click handler use $(this).attr("target", "_blank"); and then just return true after pushing the tracking command onto _gaq.
This works because open a new tab leaves the current one to finish executing the tracking call.
$(document).ready(function(){
var localserver = document.location.hostname;
// unfortunately misses if any uppercase used in link scheme
$("a[href^=http://],a[href^=https://]")
.not("a[href^=http://"+localserver+"]")
.not("a[href^=http://www."+localserver+"]")
.click(function(e){
$(this).attr("target", "_blank");
_gaq.push(['_trackEvent',
'Outgoing Click',
$(this).attr("href"),
$(this).text()
]);
return true;
});
});
With the one small downside of always opening a new tab for external links, I can't see any other problems.

How does google analytics track events when user navigates to other page inside one domain

In Google's documentation it is said that an event can be tracked in the following way:
<a onclick="_gaq.push(['_trackEvent', 'category', 'action', 'opt_label', opt_value]);">click me</a>
or older version:
<a onclick="pageTracker._trackEvent('category', 'action', 'opt_label', opt_value);">click me</a>
I was looking with Firebug to the request that are made when a click on a link and I see there aborted request:
http://www.google-analytics.com/__utm.gif?utmwv=4.7.2&utmn=907737223&....
This happens because browser unload all javascript when user navigates to a new page. How in this case event tracking is performed?
Edit:
Since one picture can be worth a thousand words...
When I click a link firebug shows me this sequence of requests (here are shown first four, after follows requests to fill page content)
The problem is that there isn't enough time for the script to finish running before the user is taken to the next page. What you can do is create a wrapper function for your GA code and in the onclick, call the wrapper function and after the GA code is triggered in your wrapper function, set a time out and update location.href with the link's url. Example:
click me
<script type='text/javascript'>
function wrapper_function(that,category,action,opt_label,opt_value) {
_gaq.push(['_trackEvent', category, action, opt_label, opt_value]);
window.setTimeout("window.location.href='" + that.href + "'", 1000);
}
</script>
code will vary a bit based on your link but hopefully you get the idea - basically it waits a little bit before taking the user to the target url to give the script some time to execute.
Update:
This answer was posted several years ago and quite a lot has happened since then, yet I continue to get feedback (and upvotes) occasionally, so I thought I'd update this answer with new info. This answer is still doable but if you are using Universal Analytics then there is a hitCallback function available. The hitCallback function is also available to their traditional _gaq (ga.js) but it's not officially documented.
This problem is answered in Google's documentation:
use
<script type="text/javascript">
function recordOutboundLink(link, category, action) {
try {
var myTracker=_gat._getTrackerByName();
_gaq.push(['myTracker._trackEvent', ' + category + ', ' + action + ']);
setTimeout('document.location = "' + link.href + '"', 100)
}catch(err){}
}
</script>
or
<script type="text/javascript">
function recordOutboundLink(link, category, action) {
try {
var pageTracker=_gat._getTracker("UA-XXXXX-X");
pageTracker._trackEvent(category, action);
setTimeout('document.location = "' + link.href + '"', 100)
}catch(err){}
}
</script>
This more or less the same as the answer from Crayon Violet, but has a nicer method name and is the official solution recommended by Google.
As above, this is due to the page being unloaded prior to the Async call returning. If you want to implement a small delay to allow gaq to sync, I would suggest the following:
First add a link and add an extra class or data attribute:
My Link
Then add into your Javascript:
$("a[data-track-exit]").on('click', function(e) {
e.preventDefault();
var thatEl = $(this);
thatEl.unbind(e.type, arguments.callee);
_gaq.push( [ "_trackEvent", action, e.type, 'label', 1 ] );
setTimeout(function() {
thatEl.trigger(event);
}, 200);
});
I don't really condone this behavior (e.g. if you are going to another page on your site, try to capture the data on that page), but it is a decent stop-gap. This can be extrapolated not just for click events, but also form submits and anything else that would also cause a page unload. Hope this helps!
I had the same issue. Try this one, it works for me. Looks like that ga doesnt like numbers as a label value. So, convert it to string.
trackEvent: function(category, action, opt_label, opt_value){
if(typeof opt_label === 'undefined') opt_label = '';
if(typeof opt_value === 'undefined') opt_value = 1;
_gaq.push([
'_trackEvent',
String(category),
String(action),
String(opt_label),
opt_value
]);
}

Resources