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=";></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'G-123456789');
</script>
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./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>
Share
Improve this question
edited Jan 15, 2022 at 6:24
Linda Lawton - DaImTo
118k39 gold badges225 silver badges501 bronze badges
asked Jan 14, 2022 at 13:17
SabrinaSabrina
3694 silver badges14 bronze badges
4
- If you inspect the view do you see the js in there? Just want to verify it is on the page but not firing. – Rockwell Rice Commented Jan 14, 2022 at 14:00
- when I inspect its not there. – Sabrina Commented Jan 15, 2022 at 18:40
-
ok so you added those lines to
application.html.erb
but it is not showing? And it doesn't work if you just refresh the page, or do a hard reload of the page? Since this is a google tracking code I just want to make sure, you did deploy the changed code to the site, correct? – Rockwell Rice Commented Jan 15, 2022 at 20:28 - I added it to application.html.erb, thats correct! The thing is that Rails 7 uses turbo which is why I think it does not work with inline js but thats just a guess. – Sabrina Commented Jan 16, 2022 at 16:15
1 Answer
Reset to default 8This method worked for me
In your site html head
<script src="https://www.googletagmanager./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)