googleTranslate 是一个 JavaScript“库”,它与 Google Cloud Translation API (v3beta1) 一起使用来翻译网页。它旨在为现已弃用的网站 Google 翻译提供替代/替代方案:https://translate.google.com/intl/en/about/website。
googleTranslate 不处理 API 身份验证。您需要向 googleTranslate 提供代理 URL 作为配置的一部分,即
apiProxy
。如果 Google Cloud Translation API 需要,此 URL 应转发来自googleTranslate
的传入 POST 负载以及有效的 OAuth 2.0 标头和 API 密钥参数。
googleTranslate 发送到proxyApi
端点的POST
负载示例:
{
"sourceLanguageCode" : " en " ,
"targetLanguageCode" : " fr " ,
"mimeType" : " text/plain " ,
"contents" :[
" Hello " ,
" World "
]
}
proxyApi
的预期响应:
{
"translations" : [
{
"translatedText" : " Bonjour "
},
{
"translatedText" : " Monde "
}
]
}
使用脚本标签在您的网站上包含 googleTranslate(最好在<HEAD>
部分):
< script type =" text/javascript " src =" ./path/googleTranslate.js " > </ script >
调用init
方法并传递所需的配置:
googleTranslate . init ( {
apiProxy : "URL_to_authenticated_API_endpoint" ,
sourceLanguage : "en" ,
} ) ;
要更改语言,请使用目标语言代码调用googleTranslate.setTargetLanguage
方法。例如法语:
googleTranslate . setTargetLanguage ( 'fr' ) ;
googleTranslate.setTargetLanguage
方法返回一个 Promise,可用于检测页面翻译操作的完成情况。如果您想显示加载屏幕或图形,这会很有用,因为 googleTranslate 可能需要几秒钟才能完成翻译过程。
翻译后将翻译设置回源语言会触发页面重新加载。
语言首选项存储在localStorage
中,键为gTranslate_lang
。这对于在用户在网站上从一个页面导航到另一个页面时保持用户偏好不变非常有用。要检索语言首选项,只需运行:
var langPreference = localStorage . getItem ( 'gTranslate_lang' ) ;
以下示例显示用户如何根据<select>
字段切换语言:
超文本标记语言
< select id =" select-lang " >
< option value =" en " > English </ option >
< option value =" fr " > French </ option >
< option value =" ru " > Russian </ option >
</ select >
JavaScript
//get <select id="select-lang"> element
var langSelectField = document . getElementById ( 'select-lang' ) ;
//get language preference and set it as default value for language `<select>` field
langSelectField . value = localStorage . getItem ( 'gTranslate_lang' ) ;
//listen for `<select>` change event
langSelectField . addEventListener ( 'change' , function ( e ) {
//translate page
var translatePromise = googleTranslate . setTargetLanguage ( e . target . value ) ;
console . log ( "translating..." ) ;
//promise returns a boolean
//indicating success/failure of translation
translatePromise . then ( function ( response ) {
if ( response ) {
console . log ( 'translation completed' )
} else {
console . log ( 'translation failed' ) ;
}
} ) ;
} ) ;
包含在您的标记中(在 googleTranslate 脚本之前)
< script >
window . googleTranslateApiProxy = "https://authenticated_api_endpoint" ;
</ script >
主脚本文件中的 Javascript(在 googleTranslate 脚本之后)
window . addEventListener ( "load" , event => {
//append translation in progress popup to body
document . body . innerHTML +=
'<div id="google_translate_popup">Translating...</div>' ;
if ( document . getElementById ( "select-lang" ) !== null ) {
//init google translate library
var gtranslateInit = googleTranslate . init ( {
apiProxy : window . googleTranslateApiProxy ,
excludeElements : [ document . getElementById ( "select-lang" ) ] ,
sourceLanguage : "en"
} ) ;
//when translation completes
gtranslateInit . then ( function ( response ) {
document . getElementById ( "google_translate_popup" ) . style . display =
"none" ;
if ( ! response ) {
alert (
"There was a problem with translating this page. Please refresh the page and try again. If the problem persists, please contact the website administrator."
) ;
}
} ) ;
var langSelectField = document . getElementById ( "select-lang" ) ;
//check language preference in localStorage
if (
localStorage . getItem ( "gTranslate_lang" ) !== null &&
localStorage . getItem ( "gTranslate_lang" ) !== ""
) {
langSelectField . value = localStorage . getItem ( "gTranslate_lang" ) ;
}
//on language preference change
langSelectField . addEventListener ( "change" , function ( e ) {
if ( e . target . value !== "" && e . target . value !== "Select language" ) {
var translatePromise = googleTranslate . setTargetLanguage (
e . target . value
) ;
document . getElementById (
"google_translate_popup"
) . style . display = "block" ;
translatePromise . then ( function ( response ) {
document . getElementById (
"google_translate_popup"
) . style . display = "none" ;
if ( ! response ) {
alert (
"There was a problem with translating this page. Please refresh the page and try again. If the problem persists, please contact the website administrator."
) ;
}
} ) ;
}
} ) ;
}
} ) ;
CSS 设置“翻译...”弹出窗口的样式
# google_translate_popup {
position : fixed;
z-index : 999 ;
background : white;
top : 0 ;
right : 50 % ;
padding : 1 rem ;
border : 1 px solid # fafafa ;
display : none;
}
参数 | 类型 | 默认 | 描述 | 例子 |
---|---|---|---|---|
apiProxy | 细绳 | empty | required 经过身份验证的端点 URL:此 URL 应转发来自 googleTranslate 的传入 POST 负载以及有效的 OAuth 2.0 标头和 API 密钥参数(如果 Google Cloud Translation API 设置为需要)。 | https://www.domain.com/google-translate-api |
translationNode | 目的 | document.body | 需要翻译的 HTML 元素。 | document.getElementById("#banner") |
observeMutationsOn | 对象数组 | [] | HTML 元素的数组,如果它们发生变化,则应进行翻译。 | [document.getElementById("#banner"), document.getElementById("#main-content") ] |
excludeElements | 对象数组 | [] | 不应翻译的元素数组。 | [document.getElementById("#user-profile"), document.getElementById("#hidden-element") ] |
sourceLanguage | 细绳 | empty | optional but recommended 。输入文本的 BCP-47 语言代码(如果已知),例如“en-US”或“sr-Latn”。 Google Cloud Translate 的语言支持中列出了支持的语言代码。如果未指定源语言,API 会尝试自动识别源语言并在响应中返回源语言。 | en |
targetLanguage | 细绳 | empty | required 用于翻译输入文本的 BCP-47 语言代码,设置为 Google Cloud Translate 的语言支持中列出的语言代码之一。 | fr |
下面是一个选择字段的示例,其中包含所有支持的语言及其代码(截至 2019 年 10 月 8 日):
< select name =" translate " id =" select-lang " >
< option selected =" selected " > Select language </ option >
< option value =" af " > Afrikaans </ option >
< option value =" sq " > Albanian </ option >
< option value =" am " > Amharic </ option >
< option value =" ar " > Arabic </ option >
< option value =" hy " > Armenian </ option >
< option value =" az " > Azerbaijani </ option >
< option value =" eu " > Basque </ option >
< option value =" be " > Belarusian </ option >
< option value =" bn " > Bengali </ option >
< option value =" bs " > Bosnian </ option >
< option value =" bg " > Bulgarian </ option >
< option value =" ca " > Catalan </ option >
< option value =" ceb " > Cebuano </ option >
< option value =" zh-CN " > Chinese (Simplified) </ option >
< option value =" zh-TW " > Chinese (Traditional) </ option >
< option value =" co " > Corsican </ option >
< option value =" hr " > Croatian </ option >
< option value =" cs " > Czech </ option >
< option value =" da " > Danish </ option >
< option value =" nl " > Dutch </ option >
< option value =" en " > English </ option >
< option value =" eo " > Esperanto </ option >
< option value =" et " > Estonian </ option >
< option value =" fi " > Finnish </ option >
< option value =" fr " > French </ option >
< option value =" fy " > Frisian </ option >
< option value =" gl " > Galician </ option >
< option value =" ka " > Georgian </ option >
< option value =" de " > German </ option >
< option value =" el " > Greek </ option >
< option value =" gu " > Gujarati </ option >
< option value =" ht " > Haitian Creole </ option >
< option value =" ha " > Hausa </ option >
< option value =" haw " > Hawaiian </ option >
< option value =" he " > Hebrew </ option >
< option value =" hi " > Hindi </ option >
< option value =" hmn " > Hmong </ option >
< option value =" hu " > Hungarian </ option >
< option value =" is " > Icelandic </ option >
< option value =" ig " > Igbo </ option >
< option value =" id " > Indonesian </ option >
< option value =" ga " > Irish </ option >
< option value =" it " > Italian </ option >
< option value =" ja " > Japanese </ option >
< option value =" jw " > Javanese </ option >
< option value =" kn " > Kannada </ option >
< option value =" kk " > Kazakh </ option >
< option value =" km " > Khmer </ option >
< option value =" ko " > Korean </ option >
< option value =" ku " > Kurdish </ option >
< option value =" ky " > Kyrgyz </ option >
< option value =" lo " > Lao </ option >
< option value =" la " > Latin </ option >
< option value =" lv " > Latvian </ option >
< option value =" lt " > Lithuanian </ option >
< option value =" lb " > Luxembourgish </ option >
< option value =" mk " > Macedonian </ option >
< option value =" mg " > Malagasy </ option >
< option value =" ms " > Malay </ option >
< option value =" ml " > Malayalam </ option >
< option value =" mt " > Maltese </ option >
< option value =" mi " > Maori </ option >
< option value =" mr " > Marathi </ option >
< option value =" mn " > Mongolian </ option >
< option value =" my " > Myanmar (Burmese) </ option >
< option value =" ne " > Nepali </ option >
< option value =" no " > Norwegian </ option >
< option value =" ny " > Nyanja (Chichewa) </ option >
< option value =" ps " > Pashto </ option >
< option value =" fa " > Persian </ option >
< option value =" pl " > Polish </ option >
< option value =" pt " > Portuguese (Portugal, Brazil) </ option >
< option value =" pa " > Punjabi </ option >
< option value =" ro " > Romanian </ option >
< option value =" ru " > Russian </ option >
< option value =" sm " > Samoan </ option >
< option value =" gd " > Scots Gaelic </ option >
< option value =" sr " > Serbian </ option >
< option value =" st " > Sesotho </ option >
< option value =" sn " > Shona </ option >
< option value =" sd " > Sindhi </ option >
< option value =" si " > Sinhala (Sinhalese) </ option >
< option value =" sk " > Slovak </ option >
< option value =" sl " > Slovenian </ option >
< option value =" so " > Somali </ option >
< option value =" es " > Spanish </ option >
< option value =" su " > Sundanese </ option >
< option value =" sw " > Swahili </ option >
< option value =" sv " > Swedish </ option >
< option value =" tl " > Tagalog (Filipino) </ option >
< option value =" tg " > Tajik </ option >
< option value =" ta " > Tamil </ option >
< option value =" te " > Telugu </ option >
< option value =" th " > Thai </ option >
< option value =" tr " > Turkish </ option >
< option value =" uk " > Ukrainian </ option >
< option value =" ur " > Urdu </ option >
< option value =" uz " > Uzbek </ option >
< option value =" vi " > Vietnamese </ option >
< option value =" cy " > Welsh </ option >
< option value =" xh " > Xhosa </ option >
< option value =" yi " > Yiddish </ option >
< option value =" yo " > Yoruba </ option >
< option value =" zu " > Zulu </ option >
</ select