googleTranslate adalah "perpustakaan" JavaScript yang digunakan dengan Google Cloud Translation API (v3beta1) untuk menerjemahkan laman web. Hal ini dimaksudkan untuk memberikan pengganti/alternatif untuk Google Terjemahan untuk situs web yang sekarang sudah tidak digunakan lagi: https://translate.google.com/intl/en/about/website.
googleTranslate tidak menangani otentikasi API. Anda harus memberikan GoogleTranslate URL proxy sebagai bagian dari konfigurasi yaitu
apiProxy
. URL ini harus meneruskan payload POST yang masuk darigoogleTranslate
bersama dengan header OAuth 2.0 yang valid dan parameter kunci API jika disetel agar diwajibkan oleh Google Cloud Translation API.
Contoh payload POST
yang dikirim oleh googleTranslate ke endpoint proxyApi
:
{
"sourceLanguageCode" : " en " ,
"targetLanguageCode" : " fr " ,
"mimeType" : " text/plain " ,
"contents" :[
" Hello " ,
" World "
]
}
Respons yang diharapkan dari proxyApi
:
{
"translations" : [
{
"translatedText" : " Bonjour "
},
{
"translatedText" : " Monde "
}
]
}
Sertakan googleTranslate di situs web Anda (idealnya di bagian <HEAD>
) menggunakan tag skrip:
< script type =" text/javascript " src =" ./path/googleTranslate.js " > </ script >
Panggil metode init
dan teruskan konfigurasi yang diperlukan:
googleTranslate . init ( {
apiProxy : "URL_to_authenticated_API_endpoint" ,
sourceLanguage : "en" ,
} ) ;
Untuk mengubah bahasa, panggil metode googleTranslate.setTargetLanguage
dengan kode bahasa target. Misalnya untuk bahasa Prancis:
googleTranslate . setTargetLanguage ( 'fr' ) ;
Metode googleTranslate.setTargetLanguage
mengembalikan janji yang dapat digunakan untuk mendeteksi penyelesaian tindakan terjemahan halaman. Ini berguna jika Anda ingin menampilkan layar atau grafik pemuatan karena GoogleTranslate memerlukan waktu beberapa detik untuk menyelesaikan proses penerjemahan.
Mengatur terjemahan kembali ke bahasa sumber setelah terjemahan memicu pemuatan ulang halaman.
Preferensi bahasa disimpan di localStorage
dengan kunci gTranslate_lang
. Hal ini berguna untuk menjaga preferensi pengguna tetap ada saat mereka bernavigasi dari halaman ke halaman di situs web Anda. Untuk mengambil preferensi bahasa, jalankan saja:
var langPreference = localStorage . getItem ( 'gTranslate_lang' ) ;
Contoh berikut menunjukkan bagaimana pengguna dapat mengganti bahasa berdasarkan bidang <select>
:
HTML
< 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' ) ;
}
} ) ;
} ) ;
Sertakan dalam markup Anda (sebelum skrip googleTranslate)
< script >
window . googleTranslateApiProxy = "https://authenticated_api_endpoint" ;
</ script >
Javascript di file skrip utama Anda (setelah skrip 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 untuk menata popup 'Menerjemahkan...'
# google_translate_popup {
position : fixed;
z-index : 999 ;
background : white;
top : 0 ;
right : 50 % ;
padding : 1 rem ;
border : 1 px solid # fafafa ;
display : none;
}
param | jenis | bawaan | keterangan | Contoh |
---|---|---|---|---|
apiProxy | rangkaian | empty | required URL titik akhir yang diautentikasi: URL ini harus meneruskan payload POST yang masuk dari googleTranslate bersama dengan header OAuth 2.0 yang valid dan param kunci API jika disetel agar diwajibkan oleh Google Cloud Translation API. | https://www.domain.com/google-translate-api |
translationNode | obyek | document.body | Elemen HTML yang memerlukan terjemahan. | document.getElementById("#banner") |
observeMutationsOn | susunan objek | [] | Serangkaian elemen HTML yang harus diterjemahkan jika bermutasi. | [document.getElementById("#banner"), document.getElementById("#main-content") ] |
excludeElements | susunan objek | [] | Array elemen yang tidak boleh diterjemahkan. | [document.getElementById("#user-profile"), document.getElementById("#hidden-element") ] |
sourceLanguage | rangkaian | empty | optional but recommended . Kode bahasa BCP-47 dari teks masukan jika diketahui, misalnya "en-US" atau "sr-Latn". Kode bahasa yang didukung tercantum dalam Dukungan Bahasa Google Cloud Translate. Jika bahasa sumber tidak ditentukan, API akan mencoba mengidentifikasi bahasa sumber secara otomatis dan mengembalikan bahasa sumber dalam respons. | en |
targetLanguage | rangkaian | empty | required Kode bahasa BCP-47 yang akan digunakan untuk terjemahan teks masukan, disetel ke salah satu kode bahasa yang tercantum dalam Dukungan Bahasa Google Cloud Translate. | fr |
Di bawah ini adalah contoh kolom pilihan yang berisi semua bahasa yang didukung beserta kodenya (per 8 Oktober 2019):
< 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