-1

Strange error, says config is undefined, but that is false:

enter image description here

There is no misspellings:

Image of Error

I am not JavaScript programmer, and that is my first extension. I hope it is a known issue. The only thing used is AJAX. The code starts like this:

var config;
var req = new XMLHttpRequest();
req.onreadystatechange = function() {
  if (this.readyState == 4 && this.status == 200) {
    config = JSON.parse(this.response);
  }
}
req.open("GET", chrome.extension.getURL('/config.json'), true);
req.send();
// here console.log(config) will return undefined.

In other words variable is assigned strangely.

  • Another time, please provide a *complete* [mcve]. At an **absolute minimum** you needed to supply the line on which the error occurred. Nowhere in your code are you trying to access the `currency` property. Thus, this is incomplete. In general, for Chrome extension debugging questions, you almost always need to supply a *manifest.json*. – Makyen Jun 28 '17 at 22:33

1 Answers1

1

Since XMLHTTPRequests are asynchronous (they don't happen instantly as the code flows) you'll have to either put the code inside their load event listener, or call a function that will have that code in it from the same event listener:

var config;
var req = new XMLHttpRequest();
req.onreadystatechange = function() {
  if (this.readyState == 4 && this.status == 200) {
    config = JSON.parse(this.response);

    // any code that uses config should be here
  }
}

or:

var config;
var req = new XMLHttpRequest();
req.onreadystatechange = function() {
  if (this.readyState == 4 && this.status == 200) {
    config = JSON.parse(this.response);

    // call doMagicStuff here
    doMagicStuff();
  }
}

function doMagicStuff() {

    // code that use config goes here

}

in the latter, you might as well just pass config as parameter to doMagicStuff.

ibrahim mahrir
  • 31,174
  • 5
  • 48
  • 73