有没有办法使用 Google 翻译插件根据访问者的 IP 和“接受语言”标头信息自动翻译我的网站?
谢谢!
这是一个老问题,根本不建议这样做(因为用户可以只使用VPN),但我很无聊,所以这就是我想出的:
代码:
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.0.js"></script></head>
<script src="https://cdn.jsdelivr.net/npm/js-cookie@rc/dist/js.cookie.min.js"></script>
<body>
<center>
<br/>
<div id="google_translate_element"></div><br/>
Country: <span id="country"></span>
<h1>Hello my friends this is a cool code.</h1>
</center>
<script>
function hc(dc){
lang = Cookies.get('language');
if(lang != dc){
window.location.hash = 'googtrans(en|' + dc + ')';
location.reload();
Cookies.set('language', dc);
}
}
$.ajax({
type: "GET",
url: "https://geolocation-db.com/jsonp/",
jsonpCallback: "callback",
dataType: "jsonp",
success: function( location ) {
$('#country').html(location.country_code);
co = location.country_code;
co = co.toLowerCase();
hc(co); // Replace here
}
});
function googleTranslateElementInit() {
new google.translate.TranslateElement({pageLanguage: 'en', layout: google.translate.TranslateElement.InlineLayout.SIMPLE}, 'google_translate_element');
}
</script>
<script src="http://translate.google.com/translate_a/element.js?cb=googleTranslateElementInit"></script>
</body>
</html>
解释:
基本上,它会向 https://geolocation-db.com/(免费)发送 Ajax 请求,并使用 json 响应,取出国家/地区代码,然后将哈希值替换为国家/地区代码,然后谷歌翻译对其进行翻译。现在这可能不是最好的方法,而且肯定存在问题,但它有效(有时😉)。
问题:
尝试一下:
复制代码并尝试一下。如果您在美国或其他没有自己语言代码的国家/地区,要测试它,只需将
hc(co);
替换为您自己的测试语言,例如 hc('ru');
。
要求:
对于 React 用户,有一个 React hook,可以使用谷歌翻译以干净的方式轻松翻译网页。
它可以让您的网页看起来干净整洁,没有谷歌翻译小部件的混乱,而且它是非常可定制的。
安装钩子库 npm 安装 use-google-translate
使用示例
import useGoogleTranslate from 'use-google-translate';
export default function Example() {
const supportedLanguages = {
en: {
code: "en",//Required
name: "English",//Optional
isRTL: false,//Optional
countryCode: "us"//Optional
},
"zh-CN": {
code: "zh-CN",
name: "中文",
isRTL: false,
countryCode: "cn"
},
ar: {
code: "ar",
name: "العربية",
isRTL: true,
countryCode: "sa"
}
}
const futureTexts = [
'This is an alert text that shows after clicking "Show Alert 1", and has been translated in the past for this time.',
{
id: 'show-alert-2', text: 'The is another alert text that shows after clicking "Show Alert 2", and has been translated in the past for this time.'
}
]
const mustTranslate = true
const {
lang,//current preferred, detected, or default language
langs,//supportedLanguages
isRTL,
detectedCountryCode,
supportsLanguage,
getLanguageData,
getTranslationFutureText,
translate,
translating,
} = useGoogleTranslate(
supportedLanguages, // *Required. The languages the translator should support
"en", // *Required. The default language. This is also the language of the page
// A text in the default language that the hook will add and hide as a div element to the page to detect when translation
// is done, by comparing the text content of this div on an interval of 200ms to this text.
"Hello world", // *Required.
// This are texts that will be displayed later. Such as in alert pop ups.
// The texts are added and hidden with unique ids as div elements to the page
// This allows the texts that will be needed in the lifespan of the page to be translated all at once,
// while the contents of these divs are returned with a simple function(getTranslationFutureText) when needed;
// to avoid layout change during user interactions that would cause another google translation process.
futureTexts,
// If set to true, the page will reload when the translation has timed out without any translation done.
// IF false, the translating state of will be set to false with no translation done.
mustTranslate, // the default is true
6000, // The translation process timeout in milliseconds. The default is 5000. That is, 5 seconds.
);
const handleAlert1 = () => {
alert(getTranslationFutureText('This is an alert text that shows after clicking "Show Alert 1", and has been translated in the past for this time.'))
}
const handleAlert2 = () => {
alert(getTranslationFutureText('show-alert-2'))
}
return (
<div>
<div style={{display: translating? "none" : "block"}}>
<h1>This is a test content for translation.</h1>
<div>Current language: {lang}</div>
<select onChange={(e) => {
translate(e.value)
}}>
{Object.keys(langs || {}).map((lng) => {
if (lng === lang) return null;
return (
<option key={index} value={lang.code}>{lang.name}</option>
)
})}
</select>
<button onClick={handleAlert1}>Show Alert 1</button><br />
<button onClick={handleAlert2}>Show Alert 2</button>
</div>
<div style={{display: !translating? "none" : "block", fontStyle: "italic"}}>...</div>
</div>
)
}