If you have files for download on your site, I’d guess that you’d want to track if people are downloading them? Fear no more, with just a few minutes work in Google Tag Manager you’ll be set. The end goal here is to make sure that we track the appropriate file types and then send that information onto Google Analytics with an event.

This will make use some simple Javascript, but do not fret, I’ll walk you through it.

The first thing you need to figure out is if you have any odd filetypes on your site, other than the regular stuff. If that’s the case, just make a note of them because you’ll need to adapt my code later on.

Javascript needed to get file extension

First of all, let’s start by creating a Variable with the type Custom Javascript in GTM. As you already know if you’ve done any custom JS in GTM before, everything needs to be wrapped inside an anonymous function and return a value. This is how our very simple code looks like.

[javascript]function() {
return {{Click URL}}.split(“.”).pop();

This requires that you have the Built-in variable {{Click URL}}  enabled, of course.

What this code does basically is that it splits the string (e.g. http://www.yourdomain.com/assets/how-to-be-awesome.pdf ) by each ‘.’ (dot).

This would give the following to work with:

  • http://www
  • yourdomain
  • com/assets/how-to-be-awesome
  • pdf

The Javascript .pop() method will return the last entry, just what we’re after.

Next we need to send this into Google Analytics

Since we now know the file extension of the link a visitor are clicking on (if present) we just have to set this up with a simple Tag and Trigger in GTM.

Tag: Event – File Download



Make sure that the Track Type is set to Event and then try using one of the following two setups pending your need when analyzing the data.

Focus on what kind of file extension that’s being downloaded:

  • Category: File Download
  • Action: {{JS – File Extension}} (The Variable you created before)
  • Label: {{Click URL}}

If the focus is more on what pages they’re on when downloading:

  • Category: File Download
  • Action: {{Page Path}}
  • Label: {{Click URL}}

Note: These are just examples, feel free to change them accordingly so they fit your needs.

Trigger: File Download

The final step is to setup the trigger for this, so select Click as a Trigger, change the Trigger Type from Click to Link Click in the configuration.



Make sure it’s enabled on all pages (Page Path equals .*) and then under Fire On make sure to select the Variable name you created earlier (e.g. JS – File Extension).

Set it to match the following regular expression, and make changes to it accordingly if you have other file extensions you need to track.


That’s all there is to it. As always, feel free to comment if you run into problems or if you have a suggestion for improvement.

Ta ta for now.