Search code examples
google-apps-scriptgoogle-analyticsgoogle-apps-marketplace

Using Google Analytics within an Editor (Google Docs) sidebar add-on


Trying to get visibility to the number of add-on users and their behaviors while using a google docs sidebar add-on I created.

I've included Global site tag (gtag.js) in sidebar.html yet there are no hits in the Real-Time overview, and no event hits when I click buttons that I've added event listners too.

Is there a special process/methodology for adding analytics to add-ons? There is nothing I can find within the add-on documentation.

sidebar.html:

<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-XXXXXXXXX-X"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());

gtag('config', 'UA-XXXXXXXXX-X');
</script>

....

....

<script>
$('#button111').click(function(){
   gtag('event', 'query');
});
</script>

Solution

  • Try to use Measurement Protocol: https://developers.google.com/analytics/devguides/collection/protocol/v1

    You can find here an example on how to use it for Apps Script. In this case it is used to track user accesses and actions in Google Analytics in a Spreadsheet, but the general concept on how to send hits to Analytics is the same:

    https://www.appsscript.it/tutorial/tracciare-in-google-analytics-gli-accessi-e-le-azioni-degli-utenti-in-uno-spreadsheet/

    Using Analytics snippet you need to specify page and title because HTMLService interfaces prevents the tracking code from doing its usual automatic detection:

    <script type="text/javascript">var GA = '<?= ga ?>';</script> //...
     <script async="" src="https://www.googletagmanager.com/gtag/js?id=YOUR_TRACKING_ID" type="text/javascript"></script> <script 
    type="text/javascript">window.dataLayer = window.dataLayer || [];
      function gtag(){dataLayer.push(arguments);}
      gtag('js', new Date());
    
      gtag('config', 'YOUR_TRACKING_ID',{
      'page_title': 'CUSTOM_TITLE',
      'page_location': SpreadsheetApp.getActive().getUrl()
    });</script>