我在我的网页上使用谷歌翻译代码,它运作良好,但如果我看看它说它只会在会话期间到期!?所以我想设置它以便它不会过期,所以当用户第一次选择回来时它就是同一种语言。
我现在正在使用它。
解决了!好的,用户可以选择一种语言,下次访问该页面时,它会被翻译成他之前选择的语言!
var ckDomain;
function googleTranslateElementInit() {
function getCookie(name)
{
var re = new RegExp(name + "=([^;]+)");
var value = re.exec(document.cookie);
return (value != null) ? unescape(value[1]) : null;
}
var kakan;
var googkakan;
kakan=getCookie("googtrans22");
$$(document).on('change', '#google_translate_element', function (e) {
setTimeout(function(){
function getCookie(name)
{
var re = new RegExp(name + "=([^;]+)");
var value = re.exec(document.cookie);
return (value != null) ? unescape(value[1]) : null;
}
googkakan=getCookie("googtrans");
document.cookie = "googtrans22="+googkakan+"; expires=Thu, 07-Mar-2047 20:22:40 GMT; path=/" + ckDomain;
document.cookie = "googtrans22="+googkakan+"; expires=Thu, 07-Mar-2047 20:22:40 GMT; path=/";
},1000);
});
for (var ckDomain = window.location.hostname.split("."); 2 < ckDomain.length;){
ckDomain.shift();
}
ckDomain = ";domain=" + ckDomain.join(".");
// domain cookie
document.cookie = "googtrans="+kakan+"; expires=Thu, 07-Mar-2047 20:22:40 GMT; path=/" + ckDomain;
// host-only cookie (with no domain name definition)
document.cookie = "googtrans="+kakan+"; expires=Thu, 07-Mar-2047 20:22:40 GMT; path=/";
new google.translate.TranslateElement({
pageLanguage: 'sv',
autoDisplay: false,
layout: google.translate.TranslateElement
}, 'google_translate_element');
}
(function() {
var googleTranslateScript = document.createElement('script');
googleTranslateScript.type = 'text/javascript';
googleTranslateScript.async = true;
googleTranslateScript.src = 'https://translate.google.com/translate_a/element.js?cb=googleTranslateElementInit';
( document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0] ).appendChild( googleTranslateScript );
})();
答案 0 :(得分:1)
显然,库被强制写入cookie以使其在会话结束时到期。
好消息是,在此之前它会读取现有的cookie,因此您可以在每次初始化调用之前提供它。
强制图书馆将瑞典语翻译成英文:
function googleTranslateElementInit() {
var ckDomain;
for (var ckDomain = window.location.hostname.split("."); 2 < ckDomain.length;){
ckDomain.shift();
}
ckDomain = ";domain=" + ckDomain.join(".");
// domain cookie
document.cookie = "googtrans=/sv/en; expires=Thu, 07-Mar-2047 20:22:40 GMT; path=/" + ckDomain;
// host-only cookie (with no domain name definition)
document.cookie = "googtrans=/sv/en; expires=Thu, 07-Mar-2047 20:22:40 GMT; path=/";
new google.translate.TranslateElement({
pageLanguage: 'sv',
autoDisplay: false,
layout: google.translate.TranslateElement
}, 'google_translate_element');
}