google-analytics.swig 1.2 KB

12345678910111213141516171819202122232425262728293031
  1. {%- if theme.google_analytics.tracking_id %}
  2. {%- if not theme.google_analytics.only_pageview %}
  3. <script async src="https://www.googletagmanager.com/gtag/js?id={{ theme.google_analytics.tracking_id }}"></script>
  4. <script{{ pjax }}>
  5. if (CONFIG.hostname === location.hostname) {
  6. window.dataLayer = window.dataLayer || [];
  7. function gtag(){dataLayer.push(arguments);}
  8. gtag('js', new Date());
  9. gtag('config', '{{ theme.google_analytics.tracking_id }}');
  10. }
  11. </script>
  12. {%- endif %}
  13. {%- if theme.google_analytics.only_pageview %}
  14. <script>
  15. function sendPageView() {
  16. if (CONFIG.hostname !== location.hostname) return;
  17. var uid = localStorage.getItem('uid') || (Math.random() + '.' + Math.random());
  18. localStorage.setItem('uid', uid);
  19. navigator.sendBeacon('https://www.google-analytics.com/collect', new URLSearchParams({
  20. v : 1,
  21. tid: '{{ theme.google_analytics.tracking_id }}',
  22. cid: uid,
  23. t : 'pageview',
  24. dp : encodeURIComponent(location.pathname)
  25. }));
  26. }
  27. document.addEventListener('pjax:complete', sendPageView);
  28. sendPageView();
  29. </script>
  30. {%- endif %}
  31. {%- endif %}