In my chrome extension project, I'm using ES6 promises to get the result of XHR from the background page and send it to the content but I'm getting undefined
as the value of response
in the content. The XHR works fine, it returns a value.
BTW, queue.js is just my small sugar for ES6 promises.
queue.js
function defer() {
let resolve = null;
let reject = null;
let promise = new Promise((_resolve, _reject) => {
resolve = _resolve;
reject = _reject;
});
return {
'promise': promise,
'resolve': resolve,
'reject': reject
};
}
module.exports = defer;
Content:
let Q = require('./queue');
let cb = Q();
function callback(response) {
if (response) {
let {result, data} = response;
if (result === 'OK') {
cb.resolve(data);
} else if (result === 'KO') {
cb.reject(data);
}
}
}
chrome.runtime.sendMessage({
'event':'some_event',
'data': {
'user': 'test',
'password': '1234'
}
}, callback);
return cb.promise;
Background:
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
$.ajax({
'url': 'I intentionally removed the URL to protect the innocent.',
'method': 'POST',
'dataType': 'json',
'contentType': 'application/json; charset=UTF-8',
'data': JSON.stringify({
'username': message.data.user,
'password': message.data.password
})
}).then((xhr) => {
sendResponse({
'result': 'OK',
'data': xhr.token
});
}).fail((xhr) => {
sendResponse({
'result': 'KO',
'data': null
});
});
});