0
I am using Google Translate on my site, and it is working perfectly, but when updating the page it returns to the default language of the site, the data appears saved in Localstorage and even then it does not return the information, my JS used:
var comboGoogleTradutor = null;
function googleTranslateElementInit() {
new google.translate.TranslateElement({
pageLanguage: 'pt',
includedLanguages: 'en,zh-CN,pt,de,es',
layout: google.translate.TranslateElement.InlineLayout.HORIZONTAL
}, 'google_translate_element');
comboGoogleTradutor = document.getElementById("google_translate_element").querySelector(".goog-te-combo");
}
function changeEvent(el) {
if (el.fireEvent) {
el.fireEvent('onchange');
} else {
var evObj = document.createEvent("HTMLEvents");
evObj.initEvent("change", false, true);
el.dispatchEvent(evObj);
}
}
function trocarIdioma(sigla) {
if (comboGoogleTradutor) {
comboGoogleTradutor.value = sigla;
changeEvent(comboGoogleTradutor);
localStorage.setItem("linguagem atual", sigla);
}
}
window.onload = () => {
const sigla = localStorage.getItem('linguagem atual');
if (sigla) trocarIdioma(sigla);
}
Then the HTML used:
<div class="list-group list-custom-small">
<a href="javascript:trocarIdioma('pt')"><img class="me-3 mt-n1" width="20" src="assets/img/translate/Brasil.png"><span>Português</span><i class="fa fa-angle-right"></i></a>
<a href="javascript:trocarIdioma('en')"><img class="me-3 mt-n1" width="20" src="assets/img/translate/United-States.png"><span>Inglês (EUA)</span><i class="fa fa-angle-right"></i></a>
<a href="javascript:trocarIdioma('de')"><img class="me-3 mt-n1" width="20" src="assets/img/translate/Germany.png"><span>Alemão</span><i class="fa fa-angle-right"></i></a>
<a href="javascript:trocarIdioma('es')"><img class="me-3 mt-n1" width="20" src="assets/img/translate/Spain.png"><span>Espanhol</span><i class="fa fa-angle-right"></i></a>
<a href="javascript:trocarIdioma('zh-CN')"><img class="me-3 mt-n1" width="20" src="assets/img/translate/China.png"><span>Chinês</span><i class="fa fa-angle-right"></i></a>
</div>
<script src="https://translate.google.com/translate_a/element.js?cb=googleTranslateElementInit"></script>