最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Make sure Google Tag Manager and Google Analytics is done before redirect - Stack Overflow

programmeradmin0浏览0评论

I have a link to my webpage where I want the user to be tracked using Google Analytics and Google Tag Manager before I redirect the user to an external page.

I want to make sure GA and GTM are done before I do the redirect. What's the best approach?

A simple approach is using a setTimeout. But is 1000ms too long or too short? Would prefer if it was possible to do redirect when tracking is actually finished?. Is GTM and GA tracking done before document ready? If not can this be forced?

<html lang="sv">
<head>
<title></title>
<meta charset="utf-8"/>
<script src="~/Scripts/jquery-2.1.0.min.js"></script>
<!-- ANALYTICS CODE -->
</head>
<body>

<!-- TAG MANAGER CODE -->

<script language="javascript">
    $(function() {
        setTimeout(function() {
            window.location.replace("");
        },1000);
    });
</script>

</body>
</html>

In the GTM bucket I have Twitter and a Facebook remarketing tag.

UPDATED SOLUTION

I've updated my solution. Since I'm mostly interested in making sure GA absolutely fires before redirect this will work better.

<html lang="sv">
<head>
    <title></title>
    <meta charset="utf-8"/>
    <script src="~/Scripts/jquery-2.1.0.min.js"></script>
    <script language="javascript">

        var redirect = function(waitFor) {
            return function(signal) {
                waitFor[signal] = 1;
                for (var s in waitFor) if (waitFor[s] == 0) return;
                _redirect();
            }
        }({timeout:0,ga:0});

        var redirected = false;
        var _redirect = function () {
            if (!redirected) {
                redirected = true;
                window.location.replace("http://@Model");
            }
        };

        (function (i, s, o, g, r, a, m) {
            i['GoogleAnalyticsObject'] = r; i[r] = i[r] || function () {
                (i[r].q = i[r].q || []).push(arguments)
            }, i[r].l = 1 * new Date(); a = s.createElement(o),
                m = s.getElementsByTagName(o)[0]; a.async = 1; a.src = g; m.parentNode.insertBefore(a, m)
        })(window, document, 'script', '//www.google-analytics/analytics.js', 'ga');
        ga('create', 'UA-47608023-1', 'tessin.se');
        ga('require', 'displayfeatures');
        ga('send', 'pageview', {
            'hitCallback': function () {
                redirect("ga");
            }
        });
    </script>

</head>
<body>

@Html.Include("google-tagmanager-redirect.html")

<script language="javascript">
    $(function () {
        setTimeout(function () { redirect("timeout"); }, 1000);
        setTimeout(function () { _redirect(); }, 3000);
    });
</script>

</body>
</html>

I have a link to my webpage where I want the user to be tracked using Google Analytics and Google Tag Manager before I redirect the user to an external page.

I want to make sure GA and GTM are done before I do the redirect. What's the best approach?

A simple approach is using a setTimeout. But is 1000ms too long or too short? Would prefer if it was possible to do redirect when tracking is actually finished?. Is GTM and GA tracking done before document ready? If not can this be forced?

<html lang="sv">
<head>
<title></title>
<meta charset="utf-8"/>
<script src="~/Scripts/jquery-2.1.0.min.js"></script>
<!-- ANALYTICS CODE -->
</head>
<body>

<!-- TAG MANAGER CODE -->

<script language="javascript">
    $(function() {
        setTimeout(function() {
            window.location.replace("http://externalwebsite.com");
        },1000);
    });
</script>

</body>
</html>

In the GTM bucket I have Twitter and a Facebook remarketing tag.

UPDATED SOLUTION

I've updated my solution. Since I'm mostly interested in making sure GA absolutely fires before redirect this will work better.

<html lang="sv">
<head>
    <title></title>
    <meta charset="utf-8"/>
    <script src="~/Scripts/jquery-2.1.0.min.js"></script>
    <script language="javascript">

        var redirect = function(waitFor) {
            return function(signal) {
                waitFor[signal] = 1;
                for (var s in waitFor) if (waitFor[s] == 0) return;
                _redirect();
            }
        }({timeout:0,ga:0});

        var redirected = false;
        var _redirect = function () {
            if (!redirected) {
                redirected = true;
                window.location.replace("http://@Model");
            }
        };

        (function (i, s, o, g, r, a, m) {
            i['GoogleAnalyticsObject'] = r; i[r] = i[r] || function () {
                (i[r].q = i[r].q || []).push(arguments)
            }, i[r].l = 1 * new Date(); a = s.createElement(o),
                m = s.getElementsByTagName(o)[0]; a.async = 1; a.src = g; m.parentNode.insertBefore(a, m)
        })(window, document, 'script', '//www.google-analytics.com/analytics.js', 'ga');
        ga('create', 'UA-47608023-1', 'tessin.se');
        ga('require', 'displayfeatures');
        ga('send', 'pageview', {
            'hitCallback': function () {
                redirect("ga");
            }
        });
    </script>

</head>
<body>

@Html.Include("google-tagmanager-redirect.html")

<script language="javascript">
    $(function () {
        setTimeout(function () { redirect("timeout"); }, 1000);
        setTimeout(function () { _redirect(); }, 3000);
    });
</script>

</body>
</html>
Share Improve this question edited Sep 7, 2015 at 13:34 Niels Bosma asked Sep 7, 2015 at 12:13 Niels BosmaNiels Bosma 11.5k30 gold badges95 silver badges150 bronze badges 2
  • 1 I don't know about GTM. But for GA, you can refer to stackoverflow.com/a/23766246/413337. It uses the hitCallback option to specify a function that is called when the Google Analytics event has been successfully sent. – Codo Commented Sep 7, 2015 at 13:11
  • Wouldn't it be better to use transport=beacon field in GA? It should guarantee delivery – Dmitry Commented Jul 19, 2018 at 4:06
Add a comment  | 

4 Answers 4

Reset to default 5

The easiest way is probably to do the redirection from within GTM.

Create a custom HTML tag with the redirection code. Then use tag sequencing to trigger the redirection tag, that way you make sure GA is triggered before the redirect.

When pushing to dataLayer with GTM you can use the eventCallback property.

dataLayer.push({
    'key1' : 'value1',
    'key2' : 'value2',
    'event' : 'fireTags',
    'eventCallback' : function() {
        alert('ALL tags which fire on {{event}} equals fireTags have now fired');
    }
});

More info: https://www.simoahava.com/gtm-tips/hitcallback-eventcallback/

One possible solution is to set the 'transport' flag, either directly in your GA code or by setting the field in GTM.

More info about that can be found here: https://developers.google.com/analytics/devguides/collection/analyticsjs/field-reference#transport. Note that GTM v2 still allows for the 'useBeacon' flag, but it is deprecated and if you code directly in GA, then you should use 'transport' instead.

For example, if directly coding in this flag:

ga('send', 'event', 'click', 'download-me', {transport: 'beacon'});

or in GTM:

This flag ensures that the hit is sent before the page navigates away.

In reference to Eike's answer. I created the following workflow to get this working;

In my code I add to the dataLayer

<script type="text/javascript">
    dataLayer.push({
        'event': 'gtm_redirect_url',
        'gtm_redirect_url': '<?php echo $url; ?>'
    });
</script>

In this case I'm using PHP to change the redirect url based on certain conditions.

Then in GTM I set up a variable called gtm_redirect_url

And a trigger also called gtm_redirect_url;

And a tag to fire the JS in an HTML snippet

All pretty simple to set up and does ensure GTM has loaded before the redirect. This method also makes it easy to add the redirect data layer tag to any page you wish.

发布评论

评论列表(0)

  1. 暂无评论