3

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?

1
  • Are you using turbolinks? Commented Feb 1, 2016 at 18:53

2 Answers 2

3

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>
Sign up to request clarification or add additional context in comments.

1 Comment

Hello from the future (it's a weird one). That HotJar page now says that they automatically handle Single Page Applications (SPAs), assuming that the URL changes. They also mention that under "Site Settings > URL CHANGES", you can tweak how the URL detection works, if e.g. your SPA uses URL fragments ("/#foo/bar") for navigation.
1

Turbolinks makes your app into an ajax single page. Only body gets reloaded, all scripts and head stays the same. There're exceptions and options on what code gets reexecuted, but anyway you do not want to add another script with hotjar code on each page navigation.

Hotjar does not yet support such apps (they say so here), so for it to work you need to disable turbolinks.

3 Comments

Can I ask for some more help? I've disable turbolinks everything starts to work, but pages looks like haven't any styles. How to fix it?
@nobilik you need to debug if css link is inserted correctly and is served. This may be because of some relative paths to/in it
It's my fall, sorry. I removed this whole string <%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track' => true %> instead a part of it. Thanks.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.