Hi I want to integrate the chat plugin Tawk.to into my rails app, however adding the script as they give it won't work with Turbolinks, I also tried to add the script into a function and call it on .ready and on page:load however it is not working, this is the original script:
var Tawk_API=Tawk_API||{}, Tawk_LoadStart=new Date();
(function(){
var s1=document.createElement("script"),s0=document.getElementsByTagName("script")[0];
s1.async=true;
s1.src='https://embed.tawk.to/API_KEY/default';
s1.charset='UTF-8';
s1.setAttribute('crossorigin','*');
s0.parentNode.insertBefore(s1,s0);
})();
I tried the following in my application.js file:
function tawk_chat(){
var Tawk_API=Tawk_API||{}, Tawk_LoadStart=new Date();
(function(){
var s1=document.createElement("script"),s0=document.getElementsByTagName("script")[0];
s1.async=true;
s1.src='https://embed.tawk.to/API_KEY/default';
s1.charset='UTF-8';
s1.setAttribute('crossorigin','*');
s0.parentNode.insertBefore(s1,s0);
})();
}
$(document).on("ready page:load", function() {
tawk_chat();
});
The above did not work. How to make work the above script with Turbolinks enabled?
There is a Ruby gem called Tawk-rails, however I installed and tested it and it has the same issue of Turbolinks, so I started to try to fix this issue.
Actually fix Tawk script for make it work with Turbolinks is very easy, you just need to set the $_Tawk
variable as undefined, so the resultant script would be:
<script type="text/javascript”>
window.$_Tawk = undefined;
var Tawk_API=Tawk_API||{}, Tawk_LoadStart=new Date();
(function(){
var s1=document.createElement("script"),s0=document.getElementsByTagName("script")[0];
s1.async=true;
s1.src='https://embed.tawk.to/#{Tawk_account_id}/default';
s1.charset='UTF-8’;
s1.setAttribute('crossorigin','*’);
s0.parentNode.insertBefore(s1,s0);
})();
</script>
You can add the above script directly in your application.js into a function and then call it on .ready or you can install this forked version of the Tawk-rails gem where I fix this issue
I already did a pull request to the original gem, so once they merge it I will update the answer.
Now the pull request is merged in to the original gem, now you can install tawk-rails gem, and Tawk.to will work as expected even with Turbolinks enabled