APIs & Integrations

Shivraj_Badu
Member

Rails 4 + Turbolinks app don't load hubspots client interface, but hard refresh is working

SOLVE

I have a rails 4 application with Turbolinks in it and I have configured Turbolinks for hubspots which will load in each page load event (note that, I have add a debugging code which is firing in each page load, so GTM is working). And I can see the hubspots script tag in my body as well as, in network tab it is doing a proper network call.

PROBLEM

  • When I refresh a page manually (hard refresh/reload) hubspot client interface (chat bubble window) shows up
  • when I visit page with Turbolinks, those network call in network tab and hubspot script tag in document tag persists, but that chat bubble window don't show up.

How to solve this problem?

UPDATE

  • Any solution for Single Page Applications (like react, angular, vuejs) are also helpful.
  • Turbolinks is making my application act like SinglePageApplication and I think that is the problem here.
1 Accepted solution
k4rth1k
Solution
Member

Rails 4 + Turbolinks app don't load hubspots client interface, but hard refresh is working

SOLVE

For anyone who is still struggling with this, I have found a workaround:
In the rails app,

In head,

 

<script type="text/javascript">
    (function () {
        document.addEventListener('turbo:before-fetch-request', function (e) {
            e.detail.fetchOptions.headers['Turbo'] = true;
        });
    })();
</script>

 

 At the end of the body tag, 

 

    <script data-turbo-permanent id="hs-preservation-script">
        function preserveHubspotChat() {
            const element = document.querySelector('#hubspot-messages-iframe-container')

            if(element) {
                // console.log('HubSpot Conversations: loaded')
                const styleTags = document.body.querySelectorAll("style[type='text/css']");
                for (const tag of styleTags) {
                if(tag.innerHTML.indexOf('hs-messages') != -1) {
                    tag.id = "hs-messages-styles"
                    tag.setAttribute('data-turbo-permanent', '')
                }
                }
                element.setAttribute('data-turbo-permanent', '')
            } else {
                // console.log('HubSpot Conversations: nope')
                setTimeout(() => {
                preserveHubspotChat();
                }, 100);
            }
        }

        function onConversationsAPIReady() {
            preserveHubspotChat()
        }
        
        if (window.HubSpotConversations) {
            onConversationsAPIReady();
        } else {
            /*
                Otherwise, callbacks can be added to the hsConversationsOnReady on the window object.
                These callbacks will be called once the external API has been initialized.
            */
            window.hsConversationsOnReady = [onConversationsAPIReady];
        }
    </script>
    <%if request.headers['Turbo']%>
        <style data-turbo-permanent id="hs-messages-styles">
        </style>
    <div data-turbo-permanent id="hubspot-messages-iframe-container"></div>
    <%end%>
    <script type="text/javascript" id="hs-script-loader" async defer src="//js.hs-scripts.com/[[id]].js"></script>

 

View solution in original post

9 Replies 9
k4rth1k
Solution
Member

Rails 4 + Turbolinks app don't load hubspots client interface, but hard refresh is working

SOLVE

For anyone who is still struggling with this, I have found a workaround:
In the rails app,

In head,

 

<script type="text/javascript">
    (function () {
        document.addEventListener('turbo:before-fetch-request', function (e) {
            e.detail.fetchOptions.headers['Turbo'] = true;
        });
    })();
</script>

 

 At the end of the body tag, 

 

    <script data-turbo-permanent id="hs-preservation-script">
        function preserveHubspotChat() {
            const element = document.querySelector('#hubspot-messages-iframe-container')

            if(element) {
                // console.log('HubSpot Conversations: loaded')
                const styleTags = document.body.querySelectorAll("style[type='text/css']");
                for (const tag of styleTags) {
                if(tag.innerHTML.indexOf('hs-messages') != -1) {
                    tag.id = "hs-messages-styles"
                    tag.setAttribute('data-turbo-permanent', '')
                }
                }
                element.setAttribute('data-turbo-permanent', '')
            } else {
                // console.log('HubSpot Conversations: nope')
                setTimeout(() => {
                preserveHubspotChat();
                }, 100);
            }
        }

        function onConversationsAPIReady() {
            preserveHubspotChat()
        }
        
        if (window.HubSpotConversations) {
            onConversationsAPIReady();
        } else {
            /*
                Otherwise, callbacks can be added to the hsConversationsOnReady on the window object.
                These callbacks will be called once the external API has been initialized.
            */
            window.hsConversationsOnReady = [onConversationsAPIReady];
        }
    </script>
    <%if request.headers['Turbo']%>
        <style data-turbo-permanent id="hs-messages-styles">
        </style>
    <div data-turbo-permanent id="hubspot-messages-iframe-container"></div>
    <%end%>
    <script type="text/javascript" id="hs-script-loader" async defer src="//js.hs-scripts.com/[[id]].js"></script>

 

Derek_Gervais
HubSpot Alumni
HubSpot Alumni

Rails 4 + Turbolinks app don't load hubspots client interface, but hard refresh is working

SOLVE

Hi @Shivraj_Badu,

Can you give me a link to an example page so that I can test this out?

0 Upvotes
tddrmllrWL
Participant

Rails 4 + Turbolinks app don't load hubspots client interface, but hard refresh is working

SOLVE

I'm having the same issue. I use Turbo, which is the newer offshoot of Turbolinks, but it uses many of the same strategies.

 

The issue is that Turbo intercepts clicks and form sumissions, transmits data over the wire, and strategically replaces elements in the <body> tag. In most cases, it simply wipes out the all the contents of the body and replaces them with the contents of the requested page.

 

So with HubSpot, everything loads and works as expected on the intial page load. But as soon as you navigate to a new page, anything that HubSpot added to the body gets replaced, while everything else added client side remains (<head> tags, JS variables, etc.). 

 

Turbo gives you some handy events to hook into, the main one being the turbo:load event, which fires whenever Turbo simulates a page change. So we can hook into this and do stuff, like re-insert the HubSpot tracking code, on every page change (though this sorta seems unnecessary since most of the HubSpot code remains).

 

For example, if you visit app.worklyfe.io/users/sessions/new, you'll see that the HubSpot chat widget appears on initial page load (it might take a bit to load as it's currently hosted on a Heroku hobby dyno). But if you click the forgot password link, the widget does not appear on the next page.

 

If I open up the JS console, I can access the HubSpotConversations variable. But none of the methods on HubSpotConversations.widget (refresh, load, open, etc.) have any effect (presumably because the widget's <iframe> is no longer there).

 

I can call HubSpotConversations.resetAndReloadWidget(), which does make the widget re-appear and functional. However, previous conversations and cookie consent is lost, so it is not a seamless experience from page to page.

 

I would hope that you guys have implemented strategies to deal with this, because it's not that different from SPA behavior. But I have not been able to figure out a reasonable solution.

StefanMM
Participant

Rails 4 + Turbolinks app don't load hubspots client interface, but hard refresh is working

SOLVE

Hey, I visited the link you posted and it looks like everything is working now.

We're facing the same issue as OP (again, Turbolinks, not Turbo), and we've followed your post and found the same issue with chat and cookie persistence.

 

Would you mind sharing how you fixed it, please?

0 Upvotes
tddrmllrWL
Participant

Rails 4 + Turbolinks app don't load hubspots client interface, but hard refresh is working

SOLVE

Huh, that's interesting. I actually haven't changed anything since I originally posted this, so HubSpot may have done something on their end to fix it. 

 

My implementation is done through Google Tag Manager, so it's a little bit more round about, but it ultimately boils down to this:

 

document.addEventListener('turbo:load', function(event) {
  var _hsq = window._hsq = window._hsq || [];

  _hsq.push(["identify", {
    email: {{user_email}},
    firstname: {{user_first_name}},
    lastname: {{user_last_name}} }
  ]);
  _hsq.push(['setPath', window.location.pathname]);
  _hsq.push(['trackPageView']);
});

 

Other than that, I unfortunately don't have much insight as to why it's working.

0 Upvotes
ZStone1
Member

Rails 4 + Turbolinks app don't load hubspots client interface, but hard refresh is working

SOLVE

Hi there. This is acutally very helpful. Having the same issue too!

I've implemented hubspot through google tag manager too. I'm interested to know about your setup. Does your hubspot tag in gtm just contain the recommended snippet?

<!-- Start of HubSpot Embed Code -->
<script type="text/javascript" id="hs-script-loader" async defer src="//js-eu1.hs-scripts.com/{id}.js"></script>
<!-- End of HubSpot Embed Code -->

Is the event listener implemented on all pages across your site?
document.addEventListener('turbo:load', function(event) {
...
}




0 Upvotes
tddrmllrWL
Participant

Rails 4 + Turbolinks app don't load hubspots client interface, but hard refresh is working

SOLVE

For the GTM code that goes in the head of my site, I added turbo:load event listener that pushes a custom event to the GTM data layer:

 

document.addEventListener('turbo:load', function(event) {
  dataLayer.push({ 'event':'turbo_load' });
});

 

Then within GTM I created a custom trigger that hooks into the dataLayer event from above:

 

tddrmllrWL_0-1652461264645.png

And my HubSpot tag in GTM looks like this:

 

tddrmllrWL_1-1652461353762.png

 

Jaycee_Lewis
Community Manager
Community Manager

Rails 4 + Turbolinks app don't load hubspots client interface, but hard refresh is working

SOLVE

Hey, @StefanMM thanks for the follow-up question. Let's see if @tddrmllrWL has any insight for us on how they worked this out.

 

Thank you! – Jaycee

linkedin

Jaycee Lewis

Developer Community Manager

Community | HubSpot

0 Upvotes
Tunch
Contributor

Rails 4 + Turbolinks app don't load hubspots client interface, but hard refresh is working

SOLVE

Was there ever a solution to this problem? 2 years later this still seems to be happening