Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using promises with chrome.runtime messaging system [duplicate]

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
        });
    });
});
like image 793
CRIS Avatar asked Dec 15 '22 06:12

CRIS


1 Answers

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

like image 57
CRIS Avatar answered Dec 31 '22 03:12

CRIS