I'm trying to make a chrome extension that searches words from the web in the Merriam-Webster dictionary, so I received an API key and started programming my background.js
for a contextMenu
.
Here is an example of a response: https://dictionaryapi.com/products/api-collegiate-dictionary
Under is a sample code I've created to get the stems of the word selected.
In my manifest.json
:
"permissions": [
"contextmenus":,
"https://dictionaryapi.com/"
]
In my background.js
:
const apikey = "my_api_key";
var url = "";
function parse(json) {
var script = JSON.parse(json);
alert(script.stems.toString())
}
function searchText(info) {
var xmlhttp = new XMLHttpRequest();
url = "https://dictionaryapi.com/api/v3/references/collegiate/json/"+info.selectionText+"?key="+apikey;
xmlhttp.open("GET", url, true)
parse(xmlhttp.responseText)
}
chrome.contextMenus.create({
title: 'Search "%s" in Dictionary',
contexts: ['selection'],
onclick: searchText
})
Result:
In this image I created an item in the contextMenu.
However, when I press it, it gives me this error:
Error in event handler: SyntaxError: Unexpected end of JSON input
It shows that JSON.parse(json)
in the function parse(json)
caused the error.
I suspect it is because of the brackets surrounding the whole JSON text.
Is there a way to get the stems
item from the text, or else a way to remove the brackets?
The example response shown here is not actually JSON, because it's missing the opening and closing braces. You will have to add the braces yourself; for example:
Change this:
To this:
I wish all questions posted by users with
1
reputation were as well written and formatted as yours, by the way.