How can I set Analytics variables with Google Tag Manager from the server?

匆匆过客 提交于 2019-12-24 04:39:12

问题


I'm using Google Optimize for creating A/B tests. I'm using it in server side mode as in this guide: https://developers.google.com/optimize/devguides/experiments

That guide shows an easy way of setting which experiment is running with which variant by rendering the JS code on the server which sets the experiment id and variant id:

  // 2. Create a tracker.
  ga('create', 'UA-XXXXX-Y', 'auto');

<?php
<<<HTML
  // 3. Set the experiment ID and variation ID.
  ga('set', 'exp', '$experimentId.$variationId');
HTML;
?>
  // 4. Send a pageview hit to Google Analytics.
  ga('send', 'pageview');

However I'm using Google Tag manager and so far haven't managed to find any guide that shows how to set variables from the server with it. ga is an undefined variable so the above doesn't work.


回答1:


Since the GTM calls the normal snippet for each tag, you can set any field the analytics snippet understands even if they are not yet automatically listed in the tag editor drop down.

For example, as a page view field:

Then set DataLayer variable so it can be received from the external source, for example:

Leading to the fields using the variable in a finished Tag:

Now, you can set DataLayer variable in the server side that will be passed through to the tag. Since I chose a page view, it would be best to pre-fill the dataLayer before loading the GTM so they are present before the initial tags fire, for example:

<!-- Google Tag Manager -->
<?php or other backend language wrapping...
 <script>window.dataLayer = [{exp:"$experimentId.$experimentVariant"}] 
 </script>
?>
<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=
'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','GTM-0');</script>
<!-- End Google Tag Manager -->


来源:https://stackoverflow.com/questions/53231442/how-can-i-set-analytics-variables-with-google-tag-manager-from-the-server

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!