-
Implementing Client-Side Waiting for Pageview Events in Google Analytics 4
Hey, so I’ve just starting messing with Google Analytics 4 on a neat little community website I manage. One of the things we’re trying to do is track each time a QR Code on a physical flyer we’re distributing is scanned. Cool, right?
The QR Code url leads to a page that loads up
gtag.js
, fires off apageview
event withutm_
codes from the url, and then uses some nifty client-side javascript to redirect users to a 3rd party ticket sales site that, unfortunately, doesn’t support Google Analytics.Managed to come up with the following page content:
<!-- Google tag (gtag.js) --> <script src="https://www.googletagmanager.com/gtag/js?id=<my_measurement_id>"></script> <script> window.dataLayer = window.dataLayer || []; function gtag() { dataLayer.push(arguments); } gtag('js', new Date()); gtag('config', '<my_measurement_id>'); </script> <script> window.addEventListener("load", function () { window.location = "<my_redirect_url>" }, false); </script>
When I check out the Debug View page in the Google Analytics portal, I can see the
pageview
events and the page does actually redirect to the right place. But here’s the thing: I basically stumbled into making this work – a fair bit of trial, error and luck was involved. So, can I really trust that this reliable? Does it just happen to work on my machine while I’m testing it, or could this be a case of “works on my machine” syndrome where things fall apart once it’s out in the big bad world?And if that’s a possibility, is there a “correct” or more reliable way to delay running the javascript till the
pageview
event has been sent?I also have this nagging question – can client-side script “observe” events that are sent, or can we set a callback for when the
pageview
event has been sent?And just tossing this out there… I’ve sort of made it work, but is there a better or simpler way to ensure a redirect only happens after the
pageview
event is sent? Open to any suggestions!
Log in to reply.