google_analytics.html 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. {{ $ga := site.Params.marketing.google_analytics | default site.GoogleAnalytics | default "" }}
  2. {{ $gtm := site.Params.marketing.google_tag_manager | default "" }}
  3. {{ if (in (slice (getenv "HUGO_ENV") hugo.Environment) "production") | and $ga | and (not $gtm) }}
  4. {{ $gtag_config := cond site.Params.privacy_pack "{ 'anonymize_ip': true }" "{}" }}
  5. <script async src="https://www.googletagmanager.com/gtag/js?id={{$ga}}"></script>
  6. <script>
  7. window.dataLayer = window.dataLayer || [];
  8. function gtag() {
  9. dataLayer.push(arguments);
  10. }
  11. function trackOutboundLink(url, target) {
  12. gtag('event', 'click', {
  13. 'event_category': 'outbound',
  14. 'event_label': url,
  15. 'transport_type': 'beacon',
  16. 'event_callback': function () {
  17. if (target !== '_blank') {
  18. document.location = url;
  19. }
  20. }
  21. });
  22. console.debug("Outbound link clicked: " + url);
  23. }
  24. function onClickCallback(event) {
  25. if ((event.target.tagName !== 'A') || (event.target.host === window.location.host)) {
  26. return;
  27. }
  28. trackOutboundLink(event.target, event.target.getAttribute('target')); // Send GA event.
  29. }
  30. gtag('js', new Date());
  31. gtag('config', '{{$ga}}', {{$gtag_config|safeJS}});
  32. // Outbound link tracking.
  33. document.addEventListener('click', onClickCallback, false);
  34. </script>
  35. {{ end }}