I am creating a redirect page where I want to transmit an event to google Analytics 4 using gtag.js
I wrote a script using the documentation (https://developers.google.com/analytics/devguides/collection/gtagjs/sending-data?hl=cs) and it works for regular links, code example:
<script type = 'text/javascript'>
gtag('config', '<COUNTER ID>', { 'transport_type': 'beacon'});
gtag('event', 'event_name', { 'event_callback' : redir() });
function redir() {
document.location = "https://www.instagram.com/<INSTAGRAM USERNAME>";
}
</script>
That is, the script sets the transport type, sends an event, and after sending the event, it calls 'event_callback', which redirects the user to the site
When I try to redirect a user to the Instagram app, and not to a web page, Google Analytics does not display either the transmitted event or the page visit
Sample code with a different link:
<script type = 'text/javascript'>
gtag('config', '<COUNTER ID>', { 'transport_type': 'beacon'});
gtag('event', 'event_name', { 'event_callback' : redir() });
function redir() {
document.location = "instagram://user?username=<INSTAGRAM USERNAME>";
}
</script>
Everything is the same, only with a different link that opens a page in the phone app. But this version does not work - the event does not come to Google analytics
What could be the problem? I tried to remove the transport type, but it was not successful. I hope for your help, any comments are welcome
You are calling the redirect in the moment invoked, but you need to call it after the event has been submitted. event_callback expects a function, you give it undefined in both cases.
The reason why your first example may work, is because sites are allowed by default to complete started requests even if you leave the page.
Opening an app directly, could interrupt the execution of the JavaScript code.
Use:
gtag('event', 'event_name', { 'event_callback' : redir });
or wrap the redirect call into another function.
gtag('event', 'event_name', { 'event_callback' : () => redir() });