4

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
        });
    });
});
CRIS
  • 335
  • 3
  • 17
  • Note: I closed this as duplicate as there is a canonical question on the topic of `return true;` - but I also upvoted both, as it's a clean question and a good self-answer. It's worth keeping, even if pointed at the canonical Q. – Xan May 10 '16 at 07:33

1 Answers1

12

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

CRIS
  • 335
  • 3
  • 17