How to force google translate to translate the page after the script loads?
10,889
Solution 1
The basic idea that you need to add cookies that google translate looks for when it's loading the element, and then you can even hide google translate elements using CSS.
Here is a short example using js.cookie:
<div class="custom-translate" st yle="display: none;" id="google_translate_element"></div>
<!-- ASYNCHRONOUS Google Translate -->
<script type="text/javascript">
function googleTranslateElementInit() {
new google.translate.TranslateElement({
pageLanguage: 'en',
layout: google.translate.TranslateElement.FloatPosition.TOP_RIGHT,
autoDisplay: false
}, 'google_translate_element');
}
(function () {
var googleTranslateScript = document.createElement('script');
googleTranslateScript.type = 'text/javascript';
googleTranslateScript.async = true;
googleTranslateScript.src =
'//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit';
(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(
googleTranslateScript);
})();
Cookies.set('GoogleAccountsLocale_session', 'iw', { expires: 999});
Cookies.set('googtrans', '/en/iw', { expires: 999});
</script>
CSS to hide the google translate elements:
<style>
.goog-te-banner-frame,.custom-translate {
display: none;
}
body {
top: 0 !important;
}
.goog-tooltip {
display: none !important;
}
.goog-tooltip:hover {
display: none !important;
}
.goog-text-highlight {
background-color: transparent !important;
border: none !important;
box-shadow: none !important;
}
</style>
Solution 2
Based on the code snippet you don't above there appears to be a couple things wrong. I would probably restructure like so...
<script type="text/javascript" src="http://translate.google.com/translate_a/element.js"></script>
<script type="text/javascript">
function googleTranslateElementInit() {
new google.translate.TranslateElement(
{
pageLanguage: 'ru',
layout: google.translate.TranslateElement.FloatPosition.TOP_LEFT,
autoDisplay: true
},
'google_translate_element'
);
}
googleTranslateElementInit();
</script>
You need to make sure that the google translate script file is loaded prior to your code attempting to execute. Then you need to execute your function...
Author by
user3016968
Updated on June 28, 2022Comments
-
user3016968 almost 2 years
<script type="text/javascript"> function googleTranslateElementInit() { new google.translate.TranslateElement( { pageLanguage: 'ru', layout: google.translate.TranslateElement.FloatPosition.TOP_LEFT, autoDisplay: true }, 'google_translate_element' ); } </script> <script type="text/javascript" src="//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit"></script>
The scripts loads, but after it loads it doesn't translate the page. I need to select the language from the selectbox. How to make it auto translate without selecting the language from the select box?