Custom page tracking URLs cannot be generated for external links when using the Universal Analytics Code

My website is equipped with Universal Analytics code, which is added to all pages:

<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-XXXXXX-XX', 'mydomain.edu');
 ga('send', 'pageview');
</script>

To track external links, I added onclick code like this:

 <a href="http://www.externalsite.com" onclick="ga('send', 'pageview', {'page': '/myexternalpage','title': 'External Page'});">External page</a>

Despite this, real-time Analytics doesn't seem to recognize these external links.

Any suggestions on how to fix this?

Answer №1

This particular issue arises due to a race condition wherein the track request fails to complete before the browser begins loading the external link.

To resolve this, you can utilize the hitCallback parameter and prevent the link from navigating by including return false in the click handler:

onclick="trackAndRedirect(); return false;"

<script>
function trackAndRedirect() {
  ga('send', 'pageview', {
    'page': '/myexternalpage',
    'title': 'External Page',
    'hitCallback': function() {
      //alert('analytics.js done sending data');
      document.location = "http://www.externalsite.com";
    }
  });
}
</script>

https://developers.google.com/analytics/devguides/collection/analyticsjs/advanced#hitCallback

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

The JavaScript code is attempting to execute a PHP script, however, I am struggling to parse the JSON data returned for use in the

As a novice, I am in the process of creating a JavaScript function that calls a PHP script every second. The PHP script retrieves values from MySQL DB, encodes them into JSON, which is then decoded by JS to display them on an HTML page. I have two queries ...

The browser has blocked access to XMLHttpRequest from a specific origin due to the absence of the 'Access-Control-Allow-Origin' header in the requested resource

After developing an Asp.Net Core 3.1 API and deploying it on the server through IIS, everything worked fine when sending GET/POST requests from Postman or a browser. However, I encountered an error with the following code: $.ajax({ type: 'GET' ...

Utilize the "incorporate" feature to include any string within an array

I am currently working on improving the search function in my application. This particular search function takes input from a search bar and is designed to handle multiple search terms. For example, it should be able to handle queries like "javascript reac ...

Incorrectly colored buttons upon clicking

I am experiencing an issue with my website where the color of the container div is not changing to the correct color when a button representing a color is clicked. Instead, it seems to be displaying the next color in the array of color codes that I have se ...

Value binding with conditional rendering in VueJS 2

My goal is to utilize VueJS 2 to render an inline condition while simultaneously adding a value to a DOM element. I am aware that I can use v-if to control the visibility of elements based on conditions, but how can I achieve an inline condition? For exam ...

Challenges encountered when creating routes in Reactjs

I'm currently working on a project and facing some challenges with managing routes. My frontend is split into two sections: one for the client side and the other for the admin panel, which is responsible for managing the client side. For example, if I ...

Invoke the onload event from document.ready using jQuery

Is it possible to trigger the onload event from within jQuery's document.ready function, such as in the example below: $(function() { onloadfunc(param); }); Comparison: <body onload = "onloadfunc(param);"> Do the above two methods achieve th ...

Styling <Link> component with styled-components: A step-by-step guide

Utilizing the Link component from @material-ui/core/Link in my TypeScript code was initially successful: <Link href="#" variant="body2"> Forgot? </Link> However, I am exploring the transition to styled-components located in a separate file. ...

How can you add draggable functionality to a Bootstrap dropdown menu?

My custom bootstrap dropdown design <div class="dropdown"> <button class="btn btn-default dropdown-toggle" type="button" id="dropdownMenu1" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true"> Dropdown <span cla ...

Showing information from asynchronous AsyncStorage.getItems in React Native

In my app, users have to validate their success on challenges by clicking a validation button which saves the "key":"value" pair of the challenge using this function: async function validate(challenge_nb) { try { await AsyncStorage.setItem(challenge_n ...

When you open the link in a new tab, the form submission does not occur

I am currently working on a form that includes a JavaScript submit function. Within the form, there are 3 anchor tags that I want to use to set different values to a hidden parameter when submitted based on the link clicked. Although the form submission w ...

managing commitments in TypeScript

Is there a way to convert a promise into a string, or is there another method for handling this result? I am encountering an error stating "You cannot use an argument of type 'Promise' for a parameter of type 'string'." const pokemonIma ...

Asynchronous Await Eagerly Anticipates Promise Status: <awaiting

Struggling to implement async/await in an express route and encountering issues. Despite referencing various SO posts, it seems like my implementation is correct. Helpers: module.exports = { facebook: function(userId, token) { return new Promise(re ...

Error message: Unable to locate module without the '.js' extension at the end of the import file path

It seems like the solution is not difficult, just something obvious. I am working on a simple TypeScript project. There are no modules involved, only TypeScript for compilation. The TS files compile into JS files in the dist folder, which are then connect ...

Guide to adding new data to a JSON array

I'm currently working on implementing a punishment system using discord.js where the actions taken against users are logged by the Discord bot in a JSON file. The structure of the punishment data is as follows: { "username": "baduser# ...

Troubleshooting Problem: Difficulty accessing Controller in AngularJS Module

I am facing difficulties with communication between my application and a module that I have developed. Below is the AngularJS module that I created. (function (document, window) { 'use strict'; var piCart = angular.module('piCart& ...

React application experiencing issues with MQTT and Mosquitto broker connectivity

Upon installing the Mosquitto broker, I successfully tested it in my command prompt. However, when I attempted to establish a connection with my React application, I encountered the error message: "WebSocket connection to 'ws://localhost:1883/' f ...

Different ways to categorize and tally a collection of objects

I'm having trouble reshaping my data in order to create a stacked bar graph. The data from the backend is structured like this: [ {date: 'January', category: 'A'}, {date: 'January', category: 'B'}, ...

Adjusting the width of innerHtml within a React router link to match the parent element's width

My current challenge involves a table where a cell is represented as a link. Within this setup, I am incorporating html content into the text of the link: <TableCell align="left" classes={{root: classes.cellPadding}}> <Link className={classes.l ...

Creating Typescript libraries with bidirectional peer dependencies: A complete guide

One of my libraries is responsible for handling requests, while the other takes care of logging. Both libraries need configuration input from the client, and they are always used together. The request library makes calls to the logging library in various ...