Different ways to monitor clicks on external links

[cross-posted on a Google Products Forum]

Currently, I have implemented the code from this website.

<script type="text/javascript">

  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'UA-XXXXXXXX-X']);
  _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>
<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>

I directly copied this code from here.

However, when I add

onClick="recordOutboundLink(this, 'Outbound Links', 'Postdoc advert');return false;"
to some links, it doesn't seem to track any clicks. I have searched online for a solution but none of them seem to work.

Can someone point out what mistake I might be making?

P.S. I found a similar complaint online at this forum post, which suggests that the code is malfunctioning.

Answer №1

Below is the method I have been using successfully. JQuery is used to attach an onclick event to any link with the class "referral". However, adding the handler directly in the HTML should also work.

  $(function() {
    $('.referral').click(function() {
      _gaq.push(['_trackEvent', 'Referral', 'Click', this.href]);
      setTimeout('document.location = "' + this.href + '"', 100);
      return false;
    });
  });

edit: There seems to be a mistake in your tracker invocation syntax. If you haven't named your tracker when setting up tracking on page load, there's no need to name it later. Refer to the documentation for _gaq.push.

Specifically:

  1. The declaration of var myTracker is unused and can be removed. Variables within the scope of recordOutboundLink are not accessible to other functions like _gaq.push.
  2. Simply use '_trackEvent' instead of 'myTracker._trackEvent'.

Answer №2

For a different option, consider utilizing this self-operated outward link script

Answer №3

To ensure successful data transmission to the server, consider setting a longer timeout of at least 2 seconds for the _gaq.push function. This allows enough time for the push operation to complete before any changes in document location interrupt the process. It is important to note that asynchronous requests are commonly utilized in this context, meaning that a brief delay can prevent the push from being cancelled prematurely.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What could be causing the chart to fail to load after I switch the JSON file

Today was my first day using highcharts and I ran into an issue when trying to use their provided code. When I changed the url of the json file, the graphic stopped loading. Original code: $.getJSON('https://www.highcharts.com/samples/data/jsonp.ph ...

Modify the information within several div sections

Is there a way to update the content inside two divs simultaneously when a button is clicked? Specifically, I want to change the bio in one div and the picture in another based on the selected player. Currently, when the button is pressed, it only loads th ...

Sequentially display and hide jQuery divs without any overlap

I'm in the process of developing a feature where a series of divs are displayed sequentially after clicking a button. Simultaneously, I am also enabling webcam capture and sending the picture to a server. The functionality is mostly working as intende ...

Oops! There seems to be a problem with your AngularJS/JavaScript code. The error message is "Uncaught ReferenceError:

As I venture into the world of AngularJS and JavaScript, I am working on creating a 'blog' using these technologies. Here is my HTML view code- <div ng-controller="Controller1"> <form ng-submit="sub()" role="form"> Title: <textar ...

Leverage the Json Object fetched from Express.js using an Angular HTML template

Having trouble retrieving JSON data from an Angular HTML template. The code is not returning the expected results, instead showing 'Object' or throwing errors after modification. server.js response.status(200).json(results.rows); product.compon ...

Ways to maintain a connection in Node.js during page reloads

My website features a real-time updated list of all online users thanks to node.js (specifically now.js) The issue arises when a user navigates the site, causing a momentary disconnect as the new page loads. This temporary disappearance from the list for ...

Obtaining the Value of Input Text

Let's say you have the following HTML code: <form> Enter hash here: <input type="text" name="hash"> <button type="submit" formaction="/tasks/">Retrieve Url</button> </form> Is there a way ...

Grab the current URL using useRouter in a Next.js app

I am using userouter to obtain the URL of the current page and then utilizing the clipboard to copy it. However, I am encountering an issue where the copied content shows as object object instead of the expected URL. Can someone please help me identify w ...

What is the best way to implement an automatic logout feature in PHP?

I develop websites with login/logout functionality. Whenever a link or button is clicked on the website, I use an ajax function to verify the user's login status and automatically log them out if their session has expired. The logout function also up ...

The FireBase dispatch functionality fails to update the real-time database

Struggling with a realtimeDB issue while using NuxtJS to manage state and send it to the DB. Saving data works fine, but editing results in a 400 BAD Request error. This error also occurs when trying to manually update information within Firebase realtime ...

AngularJS: How to automatically scroll to the bottom of a div

I cannot seem to scroll to the last message in my chat window. var app=angular.module('myApp', ['ngMaterial'] ); app.controller('ChatCtrl', function($window, $anchorScroll){ var self = this; self.messageWindowHeight = p ...

Tips for concealing a dynamic DOM element using JQuery after it has been generated

My current project involves creating a form that allows users to dynamically add text fields by clicking on an "add option" button. Additionally, they should be able to remove added fields with a "remove option" link that is generated by JQuery along with ...

Finding the occurrences of elements in an array using JavaScript

While browsing Stack Overflow, I stumbled upon a question that has yet to be answered: How can I count the occurrences of elements in a specific array using JavaScript?. let array = [6, 1, 5, 1, 1, 8, 2, 4, 6, 0] // Elements in array getOccurrence(array) ...

Render the React component asynchronously, only after the data has been successfully fetched

I am looking to display a component only after the necessary data has been fetched. If I try to load the data instantly, the component gets rendered but no information is displayed. class App extends React.Component { //typical construct fetchGameD ...

What are some methods for creating a span element that cannot be edited?

I'm having trouble with making a span inside an iframe non-editable. I've tried using pointer-events, contenteditable, and everything else, but nothing seems to work. Can someone please help me out? $('#tokens-menu-list').on('cl ...

Error encountered by React context: TypeError - Attempting to iterate over an object that is not iterable (unable to access property

I'm encountering this error: TypeError: object is not iterable (cannot read property Symbol(Symbol.iterator)) whenever I attempt to handle state using useContext. The purpose here is to initialize "tokens" as an empty array [] on page load, and then ...

Ways to invoke a controller function from a window listener function

Is there a way to trigger the close function from window.onbeforeunload even when closing the app through 'right click' -> 'close window'? It seems that this.close() is not working in this scenario, possibly due to scope issues. The ...

"Create a set of arrays within an object that are duplicates four times, and then dynamically manipulate the first item within each array

Here is the layout of my array object: const foo = {"data":[ [1,'asdf'], [2,'lorem'], [3,'impsum'], [4,'test'], [5,'omg'], ]} I am looking to replicate each array four times and increment the first item ...

What is the best way to extract numerical data from the second object in a JSON file?

How can I retrieve the data from the second object's tts number (1,152.81) and display it correctly? I attempted to use priceTag.innerHTML = data[0].tts in my javascript file below, but it doesn't seem to be working as expected. Can you help me ...

The submission of the form proceeds even with the warning displayed

I am facing an issue with a form that consists of one text field and a submit button. The user is required to input a 3-digit number, and if the number is greater than 200, a warning should be displayed. If the user clicks OK, the form should be submitted. ...