1
votes

I'm using Google Analytics (gtag.js) on a website, and I'm trying to send events.

I have an 'Add to cart' button, a simple <a class="ga-add-to-cart">Buy me!</a> element.

On click of this button, I'm firing the gtag('event' ... ) method:

$('.ga-add-to-cart').click(function(){

    productName = 'something';
    price = 123;

    gtag('event', 'add_to_cart', {
        'event_category': 'ecommerce',
        'event_label': productName,
        'value': price
    });
});

This is documented by Google here.

Of course, because I'm using an <a> tag for my button, the page is reloading after it's clicked. There's a race condition for the page reload and the gtag event.

But it's working fine when triggered in a desktop browser - I can see the HTTP request in my console and the events in Google Analytics.

However when on an iPhone, Safari browser, the event is not triggered. When inspecting the phone via desktop Safari I'm seeing that the HTTP request is cancelled.

I'm clearly doing something wrong here.

What's the best way to fire this event before page (re)load?

2

2 Answers

0
votes

Ok, so perhaps I was Googling the wrong thing. Found some helpful info here...

https://developers.google.com/analytics/devguides/collection/gtagjs/sending-data#implement_event_callback_functions

....which gives examples of the callback on the gtag('event' ...) method.

I think my solution is to either

  • Use the callback to delay the default action of my <a>, or;
  • Fire the gtag('event' ...) on the other side of the page reload
0
votes

Try explicitly setting the transport mechanism to use beacon sends.

Modify your code to use the following:

$('.ga-add-to-cart').click(function(){

    productName = 'something';
    price = 123;

    gtag('event', 'add_to_cart', {
        'transport_type': 'beacon', // Newly introduced code
        'event_category': 'ecommerce',
        'event_label': productName,
        'value': price
    });
});