Implementing Google Tag Manager with Discourse

@neil / @polusok

**Should warn you - this is hacky and might just break everything. :slight_smile: **

Javascript problems forced me to learn this:

I’ve had some success implementing GTM analytics for now.

  1. Open your analytics account and go over to the real time > content view. This should preferably be done on a development site to avoid noise from regular visitors.
  2. Configure your GTM TAG as follows:
  • Product - Google Analytics
  • Type: Universal Analytics
  • Configure Tag: Tracking ID / enable disable whatever else you want, TrackType: Pageview. I also enable Debug View to get some logs in the JS console.
  • Fire On: We’ll select a custom trigger here after completing step 3
  1. Configure a trigger as follows:
  • Event - Custom Event. I’ve called it ‘DiscourseRoute’
  • Fire On - Event Name (I’ve named it ‘PageView’ to keep things simple.
  1. Go back to the tag and select the firing trigger to be the event you configured (DiscourseRoute)

In your admin → customise → CSS / HTML → Header add the call to GTM

<!-- Google Tag Manager -->
<noscript><iframe src="//www.googletagmanager.com/ns.html?id=GTM-ND3497"
height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>
<script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
'//www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','_YOUR_CONTAINERID_**');</script>
<!-- End Google Tag Manager -->

Note that this is called ‘dataLayer’ (case sensitive…)

In your </body> section add this.

<script>
    // console.log("Getting URL");
    Ember.Application.initializer({
        name: 'googleTagManager',

        initialize: function (container, application) {
        var router = container.lookup('router:main');
            console.log('Firing Custom Pageview');
            router.on('didTransition', function () {
                    dataLayer.push({
                         'event': 'PageView'
                    });

            });
        }
    });
</script>

Note that the event is a custom event called ‘PageView’.

Save / force refresh and inspect your JS console on your discourse page. You should see the event being fire (console log output) followed by a bunch of debug output from GTM showing that it converted the custom event into a analytics pageview and the variables being passed back to analytics.

The analytics real time console should also show the pageviews being sent over.

3 Likes