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
});
});
});
I've found the answer, in developer.chrome.com
, return true;
is needed in the onMessage
so that chrome will recognise it as asynchronous. I don't know why this is the case since I called sendResponse
inside the then
of $.ajax
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With