Reputation: 589
I am building an app that uses Google API to translate text. The app works fine however if I try to translate a word that uses a foreign key, På, for example the API request seems to omit the 'å' and respond with an answer of P. This happens with all words with non-English letters.
To make things even stranger I build a small web extension that uses a window.addEventListener
to grab a word from a webpage. Using this method to send the words to the API does not cause a problem.
Here is the code that works. The content script selects a word and sends it to the background.js. The background script takes that word and sends it to the popup window. On a button click the selected word gets sent to Google API and the translation is sent back.
Content Script:
window.addEventListener('mouseup', checkWord);
function checkWord() {
let word = window.getSelection().toString();
console.log(word);
if(word.length > 0) {
let message = {
text: word,
}
chrome.runtime.sendMessage(word)
}
}
Background Script:
chrome.runtime.onMessage.addListener(receiver);
function receiver(request, sender, sendResponse) {
console.log(request);
word = request;
}
Finally my popup page function which is called on a button click:
function sendToAPI() {
let bgpage = chrome.extension.getBackgroundPage();
let word = bgpage.word;
console.log(word)
if(word.length> 0 && word.length< 100){
$.ajax({
type: 'GET',
url: `https://translation.googleapis.com/language/translate/v2?q=${word}&target=en&source=no&key=${API_KEY}`,
}).then(function(response) {
translated =response.data.translations[0].translatedText;
$('.word').empty();
$('.word').append(`${word} | ${translated}`);
return translated;
}).catch(function(err) {
sendReverse();
})
}
}
Here is the part of the other code that is not working. req.query.q
is the word that is pasted into an input field. Additionally I can remove the `req.query.q and paste the word directly into this space and the API call still does not work.
//GET request to Google Translate API
router.get('/', (req,res)=>{
console.log(req.query);
axios.get(`https://translation.googleapis.com/language/translate/v2?q=${req.query.q}&target=${req.query.target}&source=${req.query.source}&key=${process.env.GOOGLE_API_KEY}`)
.then(response => {
if(req.query.q == response.data.data.translations[0].translatedText){
res.send('reverse')
} else {
console.log(response.data.data)
res.send(response.data)
}
}).catch(err=> {
console.log(err)
})
})
Upvotes: 0
Views: 183
Reputation: 24157
You need to properly encode the special characters with encodeURIComponent()
, either like this:
....?q=${encodeURIComponent(word)}....
or separated:
var encodedWord = encodeURIComponent(word);
//
....?q=${encodedWord}....
Upvotes: 2