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?