This repository was archived by the owner on Sep 8, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
47 lines (38 loc) · 1.46 KB
/
script.js
File metadata and controls
47 lines (38 loc) · 1.46 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
async function translateText() {
const apiKey = document.getElementById('apiKey').value;
const textToTranslate = document.getElementById('textToTranslate').value;
const targetLanguage = document.getElementById('targetLanguage').value;
const translatedTextElement = document.getElementById('translatedText');
// Clear previous translated text
translatedTextElement.innerText = '';
if (!apiKey) {
translatedTextElement.innerText = 'API Key is required';
return;
}
const url = `https://translation.googleapis.com/language/translate/v2?key=${apiKey}`;
try {
const response = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
q: textToTranslate,
target: targetLanguage,
format: 'text'
})
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
if (data.error) {
throw new Error(`API error! message: ${data.error.message}`);
}
const translatedText = data.data.translations[0].translatedText;
translatedTextElement.innerText = translatedText;
} catch (error) {
console.error('Error:', error);
translatedTextElement.innerText = 'An error occurred: ' + error.message;
}
}