2

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.

enter image description here

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?

Paul T.
  • 4,703
  • 11
  • 25
  • 29
Jongwoo Lee
  • 774
  • 7
  • 20
  • 1
    Please post actual JSON (or any response, even as text) you've received yourself from the API. – GirkovArpa Sep 28 '20 at 01:51
  • You may see [here](https://dictionaryapi.com/products/api-collegiate-dictionary) for an example response, which from I seems appropriate for building the code. – Jongwoo Lee Sep 28 '20 at 08:42
  • 1
    That example is not a valid JSON as it lacks the surrounding `{` and `}`. – wOxxOm Sep 28 '20 at 09:25

1 Answers1

1

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:

parse(xmlhttp.responseText)

To this:

parse('{' + xmlhttp.responseText +'}')

I wish all questions posted by users with 1 reputation were as well written and formatted as yours, by the way.

GirkovArpa
  • 4,427
  • 4
  • 14
  • 43