Turbolinks Rails 应用程序未捕获的类型错误:无法读取属性“parentNode”

问题描述

我正在尝试在 Ruby on Rails turbolinks 站点中使用 Freshdesk 小部件。

自从我开始使用这个小部件后,在初始页面加载后导航到其他页面时,我总是在控制台中收到以下错误

http
    .userInfoEndpoint()
    .userService(customOAuth2UserService)

这是我在添加带有 id 的 div 之前的代码(我在视图中调用它的部分代码,ID 作为变量)

> 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)

查看示例

<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>

我想过使用 eventListener turbolinks:before-cache,它会查找 div 并在缓存前将其删除

这是现在的样子

<%= render "shared/freshdesk_widget",widget_id: 60000003593 %>

我面临两个错误

<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> 

和以前一样

> 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

提前致谢! 干杯

解决方法

删除元素不会删除 DOM 中的小部件,因此,据我所知,您需要做的是仅在 window.FreshworksWidget 变量未定义时才初始化小部件。

用以下几行替换所有代码:

<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>

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...