I am trying to use the Freshdesk widget in a Ruby on Rails turbolinks site.
Ever since I started using this widget, when navigating to other pages after the initial page load, I always get the following error in my console:
> VM2797 <widget_id>.js:1 Uncaught TypeError: Cannot read property
> 'postMessage' of null
> at Object.postMessage (VM2797 <widget_id>.js:1)
> at Object.widgetRenderComplete (VM2797 <widget_id>.js:1)
> at Object.handleMessage (VM2797 <widget_id>.js:1)
This was my code Before adding a div with an id(a partial that i call it in my views with and ID as a variable)
<script>
window.fwSettings={
'widget_id': <%= widget_id %>
};
!function(){if("function"!=typeof window.FreshworksWidget){var n=function(){n.q.push(arguments)};n.q=[],window.FreshworksWidget=n}}()
</script>
<script type='text/javascript' src='https://widget.freshworks.com/widgets/<%= widget_id %>.js' async defer></script>
View example
<%= render "shared/freshdesk_widget", widget_id: 60000003593 %>
I thought about using an eventListener turbolinks:before-cache, that looks for the div and remove it before-cache.
This is how it looks now
<script type='text/javascript'>
document.addEventListener("turbolinks:before-cache", function() {
const deleteable = document.getElementById("div_to_delete");
deleteable.parentNode.removeChild(deleteable);
})
</script>
<div id="div_to_delete">
<script>
window.fwSettings={
'widget_id': <%= widget_id %>
};
!function(){if("function"!=typeof window.FreshworksWidget){var n=function(){n.q.push(arguments)};n.q=[],window.FreshworksWidget=n}}()
</script>
<script type='text/javascript' src='https://widget.freshworks.com/widgets/<%= widget_id %>.js' async defer></script>
</div>
Im facing two errors
> VM49956:4 Uncaught TypeError: Cannot read property 'parentNode' of
> null
> at HTMLDocument.<anonymous> (<anonymous>:4:15)
> at
Object../node_modules/turbolinks/dist/turbolinks.js.e.dispatch
> (turbolinks.js:5)
> at r.notifyApplicationBeforeCachingSnapshot
(turbolinks.js:6)
> at r.cacheSnapshot (turbolinks.js:6)
> at r.cacheSnapshot (turbolinks.js:5)
> at r.<anonymous> (turbolinks.js:5)
> at turbolinks.js:5
And the same as before
> VM2797 <widget_id>.js:1 Uncaught TypeError: Cannot read property
> 'postMessage' of null
> at Object.postMessage (VM2797 <widget_id>.js:1)
> at Object.widgetRenderComplete (VM2797 <widget_id>.js:1)
> at Object.handleMessage (VM2797 <widget_id>.js:1)
Thanks in advance! Cheers
Removing the element doesn't removes the widget in the DOM, so, as far i can see, what you have to do is to only initialize the widget only if the window.FreshworksWidget
variable is undefined.
Replace all you code with just this lines:
<script>
if (window.FreshworksWidget === undenfined ) {
window.fwSettings={
'widget_id': <%= widget_id %>
};
!function(){if("function"!=typeof window.FreshworksWidget){var n=function(){n.q.push(arguments)};n.q=[],window.FreshworksWidget=n}}()
}
</script>