zppinto zppinto - 5 months ago 8
Javascript Question

'sendResponse' with data from a background.js function to an external page

I have an external page that sends a message to my Chrome Extension and the background script gets it and respond to it. However I want to first process the

function getID()
and only then send the response (with the ID) back to the external page.
I already tried to: set a
$.when()
and a
setTimeout
to wait for getID. But nothing works, and the response is always "undefined"...

Is there anyway to wait for the function to execute and only then send the ID back to the external page?!

External page (send Message)

var extID = "pncieomfimcmcbnbnogelnipdnkejmdf";

chrome.runtime.sendMessage(laserExtensionId, {getTargetData: true}, function(response) {
console.log(response);
});


Background script

var id;

function getID(){
$.get("url1", function( data1 ) {
//process data1 and use part of data1 on next get
$.get("url2", function( data2 ) {
//process data2 and use part of data2 on next get
$.get("url3", function( data3 ) {
//process data3 and return
return id;
});
});
});
}

chrome.runtime.onMessageExternal.addListener(
function(request, sender, sendResponse) {
getID();
sendResponse({user: id});
});

Xan Xan
Answer

You cannot return something from asynchronous functions. Please read that question before proceeding further.

You will need to call sendResponse(id) from inside the last callback. Additionally, you need to inform Chrome that you will be doing that asynchronously by returning true from the handler.

function getID(callback){
    $.get("url1", function( data1 ) {
        //process data1 and use part of data1 on next get       
        $.get("url2", function( data2 ) {
            //process data2 and use part of data2 on next get
            $.get("url3", function( data3 ) {
                //process data3 and pass the result to callback
                callback(id);
            });
        });
    });
}

chrome.runtime.onMessageExternal.addListener(function(request, sender, sendResponse) {
    getID(function(id) {
        // Will be called asynchronously from getID()
        sendResponse({user: id});
    });
    return true; // Tell Chrome we need sendResponse asynchronously
});