Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement script to Rails app?

I need to add HotJar code to my app. I did it this way:

views/services/_hotjar.html.erb

<script>
    (function(h,o,t,j,a,r){
        h.hj=h.hj||function(){(h.hj.q=h.hj.q||[]).push(arguments)};
        h._hjSettings={hjid:140457,hjsv:5};
        a=o.getElementsByTagName('head')[0];
        r=o.createElement('script');r.async=1;
        r.src=t+h._hjSettings.hjid+j+h._hjSettings.hjsv;
        a.appendChild(r);
    })(window,document,'//static.hotjar.com/c/hotjar-','.js?sv=');
</script>

views/layouts/application.html.erb

<head>
  .
  .
  <%= render partial: "services/google_analytics" %>
  <%= render partial: "services/hotjar" %>
</head>

This way HotJar works only at first opened page (I'm not sure about it, but however it doesn't work well). You may see the same thing that I've done with Google Analytic, but it works good, because here is one difference, it renders this code on every page:

views/layouts/application.html.erb

<body>
.
.
  <script>
    ga('send', 'pageview', '<%= request.path %>');
  </script>
</body>

I'm sure, this is not right way. But how to do it right?

like image 952
nobilik Avatar asked Jun 07 '26 18:06

nobilik


1 Answers

For turbolinks support, can add this snippet after your hotjar code, Hotjar on Single Page Apps

<script>
  document.addEventListener("turbolinks:load", function(event) {
    hj('stateChange', '<%=request.referer%>');
  });
</script>
like image 197
lfx_cool Avatar answered Jun 10 '26 09:06

lfx_cool