Link

Track page views in the IDRViewer with Google Analytics

To get Google Analytics to work with the IDRViewer, you can use the following code examples to add to the index.html file generated. All you need to do is add the example code into the index.html just above the closing </body> tag and then replace the ‘UA-XXXXXXXX’ sections with your Google Analytics Tracking code (check here if you need help getting this).

There are two ways to implement google analytics the newer system of gtag.js, or the previous system of analytics.js, below are examples of how to implement both of them.

gtag.js:

    <!-- Global site tag (gtag.js) - Google Analytics -->
    <script async src="https://www.googletagmanager.com/gtag/js?id=UA-XXXXXXXX"></script>
    <script>
        (function() {
            window.dataLayer = window.dataLayer || [];

            function gtag() {
                dataLayer.push(arguments);
            }

            gtag('js', new Date());

            gtag('config', 'UA-XXXXXXXX');

            function trackPageView(page) {
                gtag('config', 'UA-XXXXXXXX', {
                    'page_path': location.pathname + '?page=' + page
                });
            }

            var THRESHOLD = 1000; // Length of time (in millis) required on page to be considered a pageview
            var lastPage;
            IDRViewer.on('pagechange', function (data) {
                lastPage = data.page;
                setTimeout(function () { // Wait until the page stops changing until sending page view
                    if (lastPage === data.page) {
                        trackPageView(data.page);
                    }
                }, THRESHOLD);
            });
        })();
    </script>
    <!-- Global site tag ends -->

analytics.js:

  <!-- Google Analytics -->
  <script>
      (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','https://www.google-analytics.com/analytics.js','ga');

      ga('create', 'UA-XXXXXXXX', 'auto');
      ga('send', 'pageview');

      function trackPageView(page) {
          ga('send', {
              hitType: 'pageview',
              page: location.pathname + '?page=' + page
          });
      }

      var THRESHOLD = 1000; // Length of time (in millis) required on page required to be considered a pageview
      var lastPage;
      IDRViewer.on('pagechange', function (data) {
          lastPage = data.page;
          setTimeout(function () { // Wait until the page stops changing until sending page view
              if (lastPage === data.page) {
                  trackPageView(data.page);
              }
          }, THRESHOLD);
      });
  </script>
  <!-- End Google Analytics -->