Best Approach to track downloads in Google Analytics

Hi Everybody.

I don’t quite know which category to put this in, so I’ll put it in CMS :slight_smile:.

On one of our websites, we have some downloads links to pdf files (or other downloadable files).
As far as I could find in the documentation, no event is executed on a link to a file when the link is clicked.

What is the best way to track downloads, without adding a lot of javascript to each downloadlink?

Hey!

Google suggests that you use Event Tracking, but yeah since it’s a custom event, you have to manually track it with some JS code if you want to know how many hits your PDF links get, but you don’t necessarily need to write a line of code for each link that you have.

If you have enabled Google Analytics via Google Tag Manager, you probably don’t even need to write any piece of code. It looks like if you follow the instructions in your GTM dashboard, you can start measuring clicks on PDF links without any additional JS. (I say “looks like” because I haven’t personally tried it, but the instructions don’t mention any extra code that needs to be added).

If you have embedded the GA directly, there’s one approach I can think of which is to track make your PDFs open on a new tab so you can easily record the link click.

E.g.:
Say you have two PDF links on one page as such. Make sure you add a data-title attribute to your PDF links to track the name of the file the visitor is downloading as well as the target="_blank" attribute to make your link open in a new tab.

This method doesn’t require much Javascript, but more HTML changes if anything.

<a href="file1.pdf" data-title="File #1" target="_blank">Download File 1</a>
<a href="file2.pdf" data-title="File #2" target="_blank">Download File 2</a>

One approach you could do would be using the following script:

<script>
  const pdfLinks = document.querySelectorAll('a[href*=".pdf"]');

  function handleClick(e) {
    const fileName = e.currentTarget.dataset.title; // This is your link data-title attribute value.
    ga('send', 'event', 'Link', 'download', fileName);
  }

  pdfLinks.forEach((link, index) => {
    link.addEventListener('click', handleClick);
  });
</script>

I hope it helps.