Google 翻译脚本在 React 应用程序中加载不一致

问题描述 投票:0回答:1

我已将 Google Translate 脚本集成到我的 React 应用程序中以提供翻译功能。但是,我遇到了一个间歇性问题,即翻译器下拉列表并未在每次页面访问时始终加载。有时它加载得很好,但有时需要重新加载页面才能出现。

我已在 public 文件夹的 index.html 文件中添加了 Google Translate 脚本,并使用 React 组件中的 JavaScript 函数对其进行了初始化。尽管有这样的设置,翻译器的可用性似乎不一致。

我怀疑脚本的异步加载或初始化过程可能存在问题。我尝试确保仅在 Google 翻译脚本完全加载后才调用初始化函数,但问题仍然存在。

我正在寻求有关如何排查和解决此问题的建议,以确保用户在我的 React 应用程序的所有页面上始终可以使用 Google 翻译功能。请参阅社区右下角的蓝色类型 div 以及附加图像链接中翻译人员的支持文本google translator loaded perfectlytranslator not loaded here

我尝试使用index.html中的代码加载它,这是我的代码。

   <script>
      // Function to initialize Google Translate when the element is present
      function initializeGoogleTranslate() {
          if (document.getElementById('google_translate_element')) {
              // Load the Google Translate script dynamically
              var script = document.createElement('script');
              script.src = 'https://translate.google.com/translate_a/element.js?cb=googleTranslateElementInit';
              script.async = true;
      
             
                  googleTranslateElementInit();
             
      
              // Append the script to the document head
              document.head.appendChild(script);
          }
      }
      
      // Callback function for Google Translate initialization
      function googleTranslateElementInit() {
          new google.translate.TranslateElement({pageLanguage: 'en'}, 'google_translate_element');
      }
      
      // Call the function to initialize Google Translate
      initializeGoogleTranslate();
      </script>

这是我在 App.js 中添加的目标 div

<div id="google_translate_element"  className=" d-flex  justify-content-center align-items-center"></div> 

javascript reactjs google-translate
1个回答
0
投票

是的,曾几何时谷歌翻译很有魅力,但在过去的两三年里它变得很有趣!

这就是我所做的...请参阅下面有关如何修复它的相关评论。

let D=W.contentWindow.document; // or D=document; for your own doc.

let S='';

S=document.createElement('div');

S.id='google_translate_element';

S.style.cssText='position:fixed; left:0; top:calc(100% - 30px);';

try{D.body.appendChild(S);} catch(e) {alert(e);}


S=document.createElement('script'); S.type='text/javascript';

// This is the mod that fixed it for me... by manually calling the function after a 3 second delay...

S.text='function googleTranslateElementInit(){new google.translate.TranslateElement({pageLanguage:"en"},"google_translate_element");} setTimeout(function(){googleTranslateElementInit();},3000);';

try{D.head.appendChild(S);} catch(e) {alert(e);}


S=document.createElement('script'); S.type='text/javascript'; S.text='';

S.src='https://translate.google.com/translate_a/element.js?cb=googleTranslateElementInit';

try{D.head.appendChild(S);} catch(e) {alert(e);}
© www.soinside.com 2019 - 2024. All rights reserved.