Translate a webpage using the Google Translate widget on Window Load - Purwana Tekno, Software Engineer
    Media Belajar membuat Software Aplikasi, Website, Game, & Multimedia untuk Pemula...

Post Top Ad

Kamis, 23 Februari 2023

Translate a webpage using the Google Translate widget on Window Load

 To translate a webpage to English using the Google Translate widget on window load, you can use the following code:



<!DOCTYPE html>
<html>
<head>
	<meta charset="UTF-8">
	<title>Translate webpage to English using Google Translate widget on window load</title>
	<script>
		window.addEventListener('load', () => {
			// Load the Google Translate widget script
			const script = document.createElement('script');
			script.src = 'https://translate.google.com/translate_a/element.js?cb=googleTranslateElementInit';
			document.body.appendChild(script);
			
			// Callback function when the widget is initialized
			window.googleTranslateElementInit = () => {
				// Set the default language to translate to
				const targetLang = 'en';
				// Find the language selector and change the target language
				const select = document.querySelector('.goog-te-combo');
				select.value = targetLang;
				// Simulate a change event to trigger the translation
				const event = new Event('change');
				select.dispatchEvent(event);
			};
		});
	</script>
</head>
<body>
	<h1>Translate webpage to English using Google Translate widget on window load</h1>
	<p>This is a sample webpage to be translated.</p>
	<p>Here's another paragraph.</p>
	<div id="google_translate_element"></div>
	<script type="text/javascript">
		function googleTranslateElementInit() {
			new google.translate.TranslateElement({pageLanguage: 'auto', layout: google.translate.TranslateElement.InlineLayout.SIMPLE}, 'google_translate_element');
		}
	</script>
	<script type="text/javascript" src="//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit"></script>
</body>
</html>



This code listens for the load event on the window object, loads the Google Translate widget script, and initializes the widget to translate the page to English. The code finds the language selector in the widget and changes the target language to English. Finally, the code simulates a change event on the language selector to trigger the translation.


Note that the code assumes that the Google Translate widget script is loaded from https://translate.google.com/translate_a/element.js. If you're using a different URL, you'll need to adjust the src attribute of the script element accordingly.

Post Top Ad