Cross domain tracking on right click - google-analytics

Is there a way to pass GA cookies for cross domain tracking when user uses right click (instead of a left click) to hop domains?

It would seem that reliance is on autoLink, which decorates links automatically on left click and does not directly provide for alternative events.
Since I'm working on assumptions I'm not providing complete solutions.
Per autoLink in GA's analytics.js devguide:
// Loads the Linker plugin
ga('require', 'linker');
// Instructs the Linker plugin to automatically add linker parameters
// to all links and forms pointing to the domain "destination.com".
ga('linker:autoLink', ['destination.com'], false, true);
This will also operate on oncontextmenu so if the visitor right-clicks and selects "Open in new tab", the link is still decorated and will have the data appended.
Where decoration is required on other events, autoLinking needs to be extended by manually adding linker parameters using:
ga('linker:decorate', destinationLink);
Such a function call decorates a link based on the domains listed in the 'linker:autoLink` array above. It can be adapted to apply to all cross-domain links.
Assuming the context menu needs to be disabled:
From Andy E's answer
destinationLink.oncontextmenu = function ()
{
ga('linker:decorate', destinationLink);
console.log(destinationLink.href);
document.location = destinationLink.href;
return false;
}
That will decorate the link on right click and direct the browser to the decorated URL.
If the context menu is already disabled, abbreviating Andy E's code:
destinationLink.addEventListener('mousedown', function (e) {
console.log('mousedown', e);
if (3 == e.which) { // is it a right click
ga('linker:decorate', destinationLink)
document.location = destinationLink.href;
}
})
Note that decoration must occur as soon as possible before the visitor clicks since the parameters expire after 2 minutes.
Analytics Ninja, adapt your code to your specific requirements and if you run into further issues, please follow Philip Walton's advice

Related

"Just Links" Event firing after "History Change" event

Google Tag Manager (GTM) has a built in trigger called "Just Links". In my VueJS application, using Vue Router, GTM fires a "History Change" event before firing the "Just Links" trigger.
(the "History Change" event has nothing to do with page view events)
Because of this, the Page Path GTM data-layer variable, which is supposed to be the path that the event was triggered on, is the same value as the Click URL GTM data-layer variable, which is the href value in the <a/> tag.
For instance:
User is on /support
User clicks on link to /about
Vue Router update browsers history
History Change event fires and updates all the internal values of Google Tag Manager data layer (including location and page path)
"Just Links" event fires, Page Path and Click URL values are now both /about
I'm assuming GTM/Google Analytics have some type of built in deferment strategy in place to not interfere with other things running on the main Javascript thread. So Vue Router changes routes (hence triggering the history change) before GTM/Google Analytics fire the "Just Links" trigger event.
(Strangely enough, when you use the built in Click - All Elements in GTM, the events fire in the right order.)
Has anyone else encountered this issue and come up with any type of solution? There might be a solution with just using Click - All Elements but that by default doesn't traverse the DOM tree with <a/> and strip the href for the Click URL value, which means extracting the href value on nested elements within an <a/> doesn't work. However, Just Links does do this.
Thanks!
You can look at tag firing priority. Adjust the click tag to have higher priority than the tag that's dependent on the history change trigger.
I just ran into this problem due to a site update. Instead of switching all of my "Just Links" to "All Elements" and dealing with the many headaches, I created a new Variable to reference for the page path instead of the built-in "Page Path" Variable. This Variable is basically storing what "gtm.linkClick" now treats as the previous page path because of the History Change. I'm just at beginner-level JS, so I'm sure there is a better way to write the code, but it works.
The first step is to create a new Custom HTML Tag (name it whatever you want) set to fire on All Pages and History Changes. The Tag will first attempt to store the current page path into Session Storage, or fallback to a cookie if Session Storage is not accessible. I used the {{JS - setCookie}} Variable method that was created by Simo Ahava to set cookies. There is a 2 second delay before writing the page path to storage, which is plenty of time for the "Just Links" Trigger to fire and receive the "correct" value before it is overwritten on the next pageview or history change. I gave the sessionStorage and cookie the same name "gtm.truepage".
Custom HTML Tag
<script>
function truePage() {
try {
var page = document.location.pathname;
var storage = window.sessionStorage;
if(storage) {
setTimeout(function() {
storage.setItem("gtm.truepage", page);
},2000);
} else {
setTimeout(function() {
{{JS - setCookie}}("gtm.truepage",page,1800000,"/",window.location.hostname);
},2000);
}
} catch (e) {
}
}
truePage();
</script>
Custom HTML Tag Screenshot
1st Party Cookie Variable
The next step is to create a new 1st Party Cookie Variable named "gtm.truepage". This Variable will be used as a reference for the Custom Javascript Variable. Therefore, if you change the name, you will also need to change the name in the next part.
Cookie Variable Screenshot
Custom Javascript Variable
The final step is to create a Custom Javascript Variable (whatever name you want) that you will use for your "Clicks - Just Links" Trigger. The script will first attempt to retrieve the page path that was set by the Custom HTML Tag from Session Storage and then try the 1st Party Cookie Variable.
function() {
return window.sessionStorage.getItem('gtm.truepage') || {{gtm.truepage}};
}
Custom Javascript Variable Screenshot
You can add an after hook to your router to create a custom path variable like this:
router.afterEach((to) => {
window.vuePath = to
}
Then in Google Tag Manager create a new User-Defined Variable with the JavaScript Variable type called Vue Path. Set Global Variable Path to window.vuePath.
Now you can use Vue Path instead of Page Path in your Triggers to get the correct page path.

GTM Trigger sequence

How can I achieve this using Google Tag Manager?
I want Tag to fire if user made a seeuence of actions. For instance: visits homepage > visits certain category page > clicks on a button that expands additional content > having that content on screen visible at least 90% for 30sec or more > clicking on a button
... exactly in that order.
I would recommend you to use sessionStorage to achieve this. By passing a value to the sessionStorage for each step in the funnel you want to track you can then trigger an event once the user reached the final step.
This solution will require some javascript skills. Here is code snippet to illustrate what I mean.
var url = 'https://www.startpage.com/second';
var start_page = 'https://www.startpage.com';
var second_page = 'https://www.startpage.com/second';
var third_page = 'https://www.startpage.com/second';
if(url = start_page){
sessionStorage.setItem('funnel', 'step 1');
}
if(sessionStorage.funnel){
var previous_step = sessionStorage.funnel;
if(url === second_page && previous_step === start_page){
sessionStorage.funnel = second_page;
}else if(url === third_page && previous_step === third_page){
alert('Send event');
}
}
First of all, you need to enhance Google Tag Manager (GTM) default behavior, buy making some information persistent. By default, GTM tracks information for the current page, so you need to keep track of users making progress in this funnel across several pages. You will find some good advice and examples in this Simo Ahava article.
Second, you need to create all the relevant triggers and tags, that catch these user actions, and update current user's progress in this persistent variable, when they proceed to the next stage. You also need to consider, if there are any actions, which reset the progress, or you allow the user to take other actions as well in the meantime.
The triggers are the following:
Page view for your main page
Page view for your specified category page(s)
Click trigger on the specified element to expand your content
A visibility trigger with proper settings (reference to element, 90% visibility, 30 seconds time on screen)
Finally, a click on your specified element
You should check the progress, and update it when the proper step is taken, compared to the current state. (E.g. complete step three only when user is already on step 2.)
Obviously, you'll need to write the necessary scripts within several Custom HTML tags, but you can probably generalize the behavior with some helper functions for checking the progress, and storing any updates.

Google Analytics Event Tracking - Not working for a download link

I just finished working on a plugin for Sketch and I created a simple landing page for users to download the plugin. I want to use Google Analytics event tracking to track the downloads, but the event tracking is not working and I can't seem to figure out why.
Here is what the link looks like:
Download
Does anyone see what I'm doing wrong? Do I need to add any other code anywhere else besides the onclick attribute?
My bet is that you're facing what we call a race condition: the moment the user clicks the link, the browser initiates a page change, thus GA is interrupted before it's had a chance to send the event.
2 options
Open link in new tab: add target="_blank" to your links so they open in a new tab and don't interrupt GA in the current tab.
Prevent Default + Hitcallback: you can use a custom function for onClick that will prevent the link from opening by default (return false;), trigger the GA event, and use GA's hitCallback to trigger the page change programatically.
For option 2 there are different ways of doing it (since it's custom code). Here is an example from Google:
https://support.google.com/analytics/answer/1136920?hl=en
<script>
/**
* Function that tracks a click on an outbound link in Analytics.
* This function takes a valid URL string as an argument, and uses that URL string
* as the event label. Setting the transport method to 'beacon' lets the hit be sent
* using 'navigator.sendBeacon' in browser that support it.
*/
var trackOutboundLink = function(url) {
ga('send', 'event', 'outbound', 'click', url, {
'transport': 'beacon',
'hitCallback': function(){document.location = url;}
});
}
</script>
You'll also need to add (or modify) the onclick attribute to your links. Use this example as a model for your own links:
Check out example.com

How to incorporate Google Analytics Event Tracking with Anythingslider

I am looking for some clues on where to add Google Analytics Event Tracking to a page that has AnythingSlider installed. I have a slider that does not autoscroll and you have to click the navigation buttons for the slides to move. I wish to track these clicks. I would also like to track if a visitor clicks on a link within a slide.
I am wishing to use Google's InPage Analytics to track visitor click behavior and workout what items (images & phrases) catch the attention of the visitor in order to make better lead funnels.
I did try the Event tracking guide from Google before posting here, but I was unsure of where to pickup the navigation clicks from the slider.
add this to any a href in your html
onClick="_gaq.push(['_trackEvent', 'Slider','Panelno:x', 'blah']);"
Untested (I'm about to do this myself) but the API suggests to me that I should use the onSlideComplete callback, e.g. (assuming you've set up the names of your panels in an array called pages).
onSlideComplete : function(foo) {
_gaq.push(['_trackEvent', 'Slider','Panelno:'+slider.currentPage, pages[index - 1]]);
}
EDIT: Be careful with onSlideComplete, it seems to fire off too often. Set a var to tell it not to refire, and reset the var with onSlideBegin.
onSlideBegin : function(e, slider) {
refire = 1;
},
onSlideComplete : function(slider) {
if (refire) {
_gaq.push(['_trackEvent', 'Slider','Panelno:'+slider.currentPage, pages[slider.currentPage - 1]]);
refire=0;
}
}

How to track file downloads

I am running a Image gallery website which can be used to download images... say if you call somedomain.com/flowers it will return a zip file containing top 10 flower images....
Now my requirement is to track these downloads.. how can I implement this.. any possibility to use Google Analytics.
Update:
I forgot to add another important thing because of which I can't use custom events...
It is not necessary to always click and download a zip file.... I have created a little app (AIR application) to directly download the file.In that case I can't able to use any GA script... I want to know whether it is possible to use GA in this case if yes then how to implement?
Fire a custom event when the user clicks on the download link.
You need to associate google analytics events with your links. Please read
http://code.google.com/apis/analytics/docs/tracking/eventTrackerOverview.html
http://code.google.com/apis/analytics/docs/tracking/eventTrackerGuide.html
The two basic ways are event tracking (registering the click) and the other is by a virtual 'pageview'. The problem with the first is that clicks are less reliably measured; the problem with the second when the user clicks the link, trackPageview might not have time to execute. One common solution is to use the virtual pageview technique and add a small timer to cause a 100 millisecond delay:
In practice, you need two pieces of js code--one to modify the a href tag by binding the onclick handler to a function, and the other to create that function: (shown first, below)
<script type="text/javascript">
function obl(this) {
try {
var pageTracker=_gat._getTracker("UA-XXXXXXX-X");
pageTracker._trackPageview("a_download_link");
setTimeout('document.location = "' + this.href + '"', 100)
}catch(err){}
}
</script>
<a href="a_download_link" onclick='obl(this);return false;'>Click Here to Download</a>
If you are using the newest (asynchronous GA Code) replace the function above with this one:
<script type="text/javascript">
function obl(this) {
_gaq.push(['_trackPageview', 'a_download_link'+this.href]);
setTimeout('document.location = "' + this.href + '"', 100)
}
</script>
One complication this technique introduces is that it causes your downloads to be co-mingled with your page view totals. As long as you are aware of it, it's trivial to deal with--just create a filter to remove these 'false' page views. Similarly, to actually show the downloads in the GA Browser, you might want to create a separate profile (e.g., 'Downloads') and then create an 'Advanced Segment' by filtering all page views except the download page views.

Resources