I’m working on a vocabulary spreadsheet in Google Sheets and need to build custom functions that pull word meanings, related terms, and opposite terms from a dictionary web service.
I have these scripts in my Apps Script project but when I try to use them in my sheet cells, I keep getting an error that says “fetch is not defined”. Can someone help me fix this issue?
Here’s my main function:
/**
* Executes JavaScript code
* @param {string} script The script to run
* @return Result of the executed script
* @customfunction
*/
function EXECUTEJS(script) {
return eval(script);
}
For word meanings:
const SECRET_KEY = 'my-api-key';
const TARGET_WORD = 'happy';
fetch(`https://api.dictionary.com/v2/entries/english/${TARGET_WORD}?key=${SECRET_KEY}`)
.then(result => result.json())
.then(info => {
const meaning = info[0].definitions[0];
console.log(meaning);
})
.catch(err => console.log(err));
For similar words:
const SECRET_KEY = 'my-api-key';
const TARGET_WORD = 'run';
fetch(`https://api.dictionary.com/v2/entries/english/${TARGET_WORD}?key=${SECRET_KEY}&related`)
.then(result => result.json())
.then(info => {
const similarWords = info[0].related.similar.join(', ');
console.log(`Similar: ${similarWords}`);
})
.catch(err => console.log(err));
For opposite words:
const SECRET_KEY = 'my-api-key';
const TARGET_WORD = 'hot';
fetch(`https://api.dictionary.com/v2/entries/english/${TARGET_WORD}?key=${SECRET_KEY}&opposites`)
.then(result => result.json())
.then(info => {
const oppositeWords = info[0].related.opposites.join(', ');
console.log(`Opposites: ${oppositeWords}`);
})
.catch(err => console.log(err));