I have a chrome extension that calls out to a server Back End. It works fine when I have the back end adress hardcoded into the code, but whilst trying to move that out into a user configurable setting it fails. The problem appears to be AJAX's async behaviour causing the issue because JQuery is sending off the AJAX 'GET' request before the code reaches into the Chrome Storage to get the current setting.
Within a Chrome Extension (popup.js) Using AJAX 3.5.1
The AJAX call is very simple:
$.ajax({
url: getCrumbURL(),
type: 'get',
data: {},
error: function(XMLHttpRequest, textStatus, errorThrown) {
console.log("Status: " + textStatus);
console.log("Error: " + errorThrown);} ,
success: function (data) {
console.log(data);}});
and the getCrumbURL function is this:
function getCrumbURL(){
var myBackend;
chrome.storage.sync.get({ "backEndServerURL": 'Not set yet' }, function (result) {
myBackend = "http://" + result.backEndServerURL + "crumbIssuer/api/json";
console.log("1. Requesting crumb from: " + myBackend);
})
console.log("2. Requesting crumb from: " + myBackend);
return myBackend;
}
The AJAX function calls its own page (which I believe is the default if the url:
is not set) so I think it's failing because it's not waiting for the call to chrome.storage.sync.get
before trying to send the AJAX call. I suspect this because when I look at the output on the console, by two debus messages arrive in the reverse order:
- Requesting crumb from: undefined
- Requesting crumb from: http://192.168.99.100:8080/crumbIssuer/api/json
I know AJAX is Async, but this is from WITHIN the AJAX call (as opposed to elsewhere in the code).
Can anyone explain whether my assumption is correct and whether there's a way to force the AJAX to wait for the chrome.storage.sync.get to return it's value (as it provides the URL!). Many thanks Matt
EDIT 1: I have read a number of SO questions that explain how to work with a response from an Aysnc call (for example using a Promise) but (and this may be my lack of experience) I cannot see how this applies here. The issue is not trying to do something AFTER an ASync call (the $.AJAX) but BEFORE it takes place (so that it has the URL pulled from the Chrome Storage). If I'm missing the answer in the other SO questions, please could someone help me out by explaining how this would work in the situation posted above? Many thanks.