Multi-Language Translation App JavaScript, API
👤 Sharing: AI
```javascript
// This code provides a basic structure and requires an API key and setup for a translation service like Google Translate API.
// Remember to install necessary dependencies like 'node-fetch' if you're running this in a Node.js environment: npm install node-fetch
// Replace 'YOUR_API_KEY' and adjust the API endpoint as needed for your chosen service.
import fetch from 'node-fetch';
const apiKey = 'YOUR_API_KEY'; // Replace with your actual API key
const apiUrl = 'https://translation.googleapis.com/language/translate/v2'; // Example: Google Translate API endpoint
async function translateText(text, targetLanguage, sourceLanguage = 'auto') {
try {
const response = await fetch(`${apiUrl}?key=${apiKey}`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
q: text,
target: targetLanguage,
source: sourceLanguage,
format: 'text', // Or 'html' if your input is HTML
}),
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
if (data.error) {
throw new Error(`API Error: ${data.error.message}`);
}
return data.data.translations[0].translatedText;
} catch (error) {
console.error("Translation error:", error);
return `Translation failed: ${error.message}`;
}
}
async function main() {
const textToTranslate = "Hello, how are you?";
const targetLanguage = "es"; // Spanish
//const targetLanguage = "fr"; // French
//const targetLanguage = "de"; // German
try {
const translatedText = await translateText(textToTranslate, targetLanguage);
console.log(`Original text: ${textToTranslate}`);
console.log(`Translated text (${targetLanguage}): ${translatedText}`);
} catch (error) {
console.error("Error during translation:", error);
}
}
// Call main function if running directly
if (typeof window === 'undefined') {
main();
}
// Example usage in a browser environment: (Requires browser-compatible 'fetch' or XMLHttpRequest)
// Make sure to handle API key security properly in a browser environment.
// async function translateTextBrowser(text, targetLanguage, sourceLanguage = 'auto') {
// const url = `${apiUrl}?key=${apiKey}&q=${encodeURIComponent(text)}&target=${targetLanguage}&source=${sourceLanguage}`;
// const response = await fetch(url, {method: 'GET'});
// const data = await response.json();
// if (data.error) {
// throw new Error(`API Error: ${data.error.message}`);
// }
// return data.data.translations[0].translatedText;
// }
// async function handleTranslation() {
// const inputText = document.getElementById('inputText').value;
// const targetLang = document.getElementById('targetLanguage').value;
// try {
// const translated = await translateTextBrowser(inputText, targetLang);
// document.getElementById('outputText').textContent = translated;
// } catch (error) {
// document.getElementById('outputText').textContent = `Error: ${error.message}`;
// }
// }
// Example HTML (for browser)
/*
<!DOCTYPE html>
<html>
<head>
<title>Translation App</title>
</head>
<body>
<h1>Translation App</h1>
<label for="inputText">Text to Translate:</label><br>
<input type="text" id="inputText" value="Hello, world!"><br><br>
<label for="targetLanguage">Target Language:</label><br>
<select id="targetLanguage">
<option value="es">Spanish</option>
<option value="fr">French</option>
<option value="de">German</option>
</select><br><br>
<button onclick="handleTranslation()">Translate</button><br><br>
<label for="outputText">Translated Text:</label><br>
<div id="outputText"></div>
<script>
// Include the translateTextBrowser and handleTranslation functions here, or link to an external script file.
</script>
</body>
</html>
*/
export { translateText }; // Export the translateText function if needed for use in other modules.
```
👁️ Viewed: 20
Comments