Refreshing Hubspots chat widget on SPA after page transition

584 Views Asked by At

I implemented Hubspot on a Vue-SPA.

It works as expected. But the chat-widget isn't tracking the SPA page transitions.

The docs suggest to use window.HubSpotConversations.widget.refresh(); to handle untracked page transitions on SPAs.

If the the set delay for showing the welcome text is not over yet.
The refresh() will trigger the wrong chat-flow.

But if it's already over, this works.
Kind of.
Because if the new welcome text is longer than the old one, it gets cropped.

The old welcome text
The new one but cropped
The new one displayed correctly



Another Problem: An already started conversation via chat wont be ended by refresh() but if the chat was open it will be closed after. And I can't figure out how to tell the widget to reopen as you would expect.

2

There are 2 best solutions below

0
On

As described here: https://developers.hubspot.com/docs/api/events/tracking-code, you need to handle route change events in your SPA and then call trackPageView like this:

var _hsq = window._hsq = window._hsq || [];
_hsq.push(['trackPageView']);

you may also want to call setPath in some scenarios as described in the doc.

0
On

I'm a frontend developer at Webz.io and we've been trying to implement the Hubspot Chatflow in our Next.js marketial website. However, the routing system in Next.js is not caused by page refresh, so the Chatflow doesn't always know if it is supposed to be rendered on the relevant page or not. Our Marketing Operations specialist created the Chatflow for the website and determined the URLs that the bot is supposed to appear at, but sometimes it glitched to other pages, and sometimes it didn't appear on relevant pages because the routing of Next.js is not forcing Hubspot's bot to recheck the current URL. After some research, I found a solution to this issue that I wanted to share with the community.

Solution: refresh

To solve this issue, I attached a simple code line to the Next.js router that invokes an HTTP request to Hubspot to revalidate the URL and refresh the state of the chatbot. Here's the code snippet:

useEffect(() => {
  if (window.HubSpotConversations && window.HubSpotConversations.widget) {
    window.HubSpotConversations.widget.refresh();
  }
}, [router]);

or if you would like to make it shorter:

useEffect(() => {
  window.HubSpotConversations?.widget?.refresh();
}, [router]);

This useEffect hook is added to the _app.js file and triggers a refresh of the Hubspot Chatflow on every route change, ensuring that the chatbot appears on the correct pages.

While this solution worked for us, it would be helpful if Hubspot could add this snippet to their documentation or create an NPM package that includes this useEffect hook inside a function called refreshChatFlow or something similar. This would make it easier for other developers to implement the Hubspot Chatflow on Next.js websites without encountering this issue.