简体   繁体   中英

google analytics tag not working in rails 7 app

Hi have a rails 7 application and want to place my google analytics tag js snippet.

What I tried was just adding this script to the application.html.erb, which does not work (probably related to hotwire / turbo)?:

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

  gtag('config', 'G-123456789');
</script>

This method worked for me

In your site html head

<script src="https://www.googletagmanager.com/gtag/js?id=G-111111111" data-turbo-track="reload" async></script>

and in the application.js

document.addEventListener("turbo:load", function(event) {
  window.dataLayer = window.dataLayer || []
  function gtag(){dataLayer.push(arguments)}
  gtag('js', new Date())
  gtag('config', 'G-111111111', {'page_location': event.detail.url})
}, false)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM