How to convert web page to a specific language automatically using Google TranslateElement?

40 views Asked by At

I need to translate full page to a specific language based on Button Click - I am utilizing Google TranslateElement for this but I am not able to achieve the results

Here's my Change Language Function

const changeLanguage = () => {
  const langCode = 'it';

  // Check if the Google Translate API is loaded
  if (window.google && window.google.translate) {
    try {
      // Get the Google Translate element
      const translateElement = document.getElementById(
        'google_translate_element'
      );

      // Check if the element is present
      if (translateElement) {
        // Clear the content of the element
        translateElement.innerHTML = '';

        // Initialize the TranslateElement with the new language
        new google.translate.TranslateElement({
            defaultLanguage: langCode,
            pageLanguage: langCode
          },
          'google_translate_element'
        );

        console.log('Language changed successfully');
      } else {
        console.error('Element with id "google_translate_element" not found');
      }
    } catch (error) {
      console.error('Error changing language:', error);
    }
  } else {
    console.error('Google Translate API not loaded');
  }
};

Goal is to use FREE tool that can convert whole web page on FE to any specific language using a custom button click. I am using Next.js for FE.

I don't want to use paid tool including google translate API.

0

There are 0 answers