fgblomqvist
fgblomqvist

Reputation: 2424

Google Analytics send event fails sometimes

I am trying to log an event each time a user downloads a specific file, but the request to analytics servers gets cancelled every now and then (the download starts though).

Here is the code:

ga('send', 'event', {
    'eventCategory': 'Addon',
    'eventAction': 'Download',
    'hitCallback': function() {
        document.location = $scope.file.file_url;
    }
});

(The file resides on a different host in case that info matters)

I suppose the request is cancelled by the browser, but why is it happening and what can I do to prevent it?

Upvotes: 0

Views: 268

Answers (2)

fgblomqvist
fgblomqvist

Reputation: 2424

I solved the problem by adding the download attribute to my a tag:

<a href="mydownloadurl" download>Download</a>

I noticed that I was getting this message when starting the download:

Resource interpreted as Document but transferred with MIME type application/octet-stream

After googling around I found the solution, which was to add the download attribute. Turns out that the ga request is no longer cancelled with that in place. The browser must have been confused by that error and cancelled all ongoing requests (or something). I did some testing now and out of about 20 ga calls all of them were successful.

Upvotes: 1

dm-guy
dm-guy

Reputation: 566

Does the user stays on the same page during the download? If the user is redirected to another page (such as a PDF preview of the file that she downloaded, or a thank you page) then the code might not have time to execute. Use JS setTimeout to delay the redirection.

Beyond that, more info and examples are needed in order to troubleshoot your issue.

Upvotes: 1

Related Questions