Search code examples
ruby-on-railsturbolinkssmooch

Using Smooch widget with turbolinks


I'm developing a rails app using turbolinks, and I'm trying to get the Smooch widget to work along with turbolinks.

The problem is as turbolinks replaces the body of the page on each page load, the widget I initialized gets removed from the page.

I tried using the embedded mode and setting data-turbolinks-permanent like this:

Smooch.init({ appToken: token, embedded: true });  
Smooch.render(document.getElementById('smooch-container'));

<div id='smooch-container' data-turbolinks-permanent></div>

But it seems that smooch doesn't even insert the widget within this container:

<div id="smooch-container" data-turbolinks-permanent=""></div>
<div id="sk-holder">...</div>

How can I use components that I need to persist across page loads with turbolinks?


Solution

  • What I did was to use the private _container variable where the React component is rendered:

    $(document).on('turbolinks:before-cache', function () {
      Smooch._container && $(Smooch._container).detach();
    });
    
    $(document).on('turbolinks:render', function () {
        Smooch._container && $('body').append(Smooch._container);
    });
    

    We append the component to the DOM when a new page is loaded.

    Animations will not properly work with this though, so I had to overwrite the CSS animations and use opacity to show/hide the component.