Background: I've (very) recently started using Google Analytics 4 for a small community website to track how many times a QR Code is scanned on a physical advertising flier we're going to be distributing.
The url in the QR Code basically points to a page that loads gtag.js
which sends a pageview
event with the utm_
codes from the querystring in the url, and then some client-side javascript redirects the user to a 3rd party ticket sales site that doesn't support Google Analytics.
This all seems to works 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>
I see pageview
events in the Debug View page in the Google Analytics portal and the page redirects to the correct location, but I've arrived at this through trial, error and no small amount of stumbling luck, so what I'd like to understand is whether this is a reliable way to wait for the pageview
event to be sent before the client-side redirect happens, or whether it just happens to work right now on my machine while I'm testing it, but may break when released into the wild...
And if the latter, is there a "correct" way to delay running some javascript until the pageview
event has been sent?
For example, can client-side script "observe" events that are sent, or is there a callback that can be registered for when the pageview
event has been sent?
(This may also be an XY Problem in that I've started down this route and gotten it sort-of working - if there's a better / simpler way to ensure a redirect only happens after the pageview
event is sent I'd be happy to hear that as well...)