Chrome extension function not returning value to caller function

19 Views Asked by At

I have a chrome extention that is communicating with the background tab to get a certain sid, then I am trying to create some buttons with the sid. Here is the function that calls the background tab:

function call_background_tab(req) {
    switch (req) {
        case "zbx_sessionid":
            chrome.runtime.sendMessage({item: req}, function(response) {
                var rsp = response["response"][0]["value"];
                console.log("call_background_tab: " + rsp); // <- this works
                return rsp;
            });
    }
}

I am calling the function in the following code:

let sid = call_background_tab("zbx_sessionid");
console.log("main: " + sid); // <- this does not work, returns undefined
add_CheckNow_Button(sid);

After refreshing the page, in the console, I see:

main: undefined
call_background_tab: bfe92fcafbc7d4e09fccc8de595dcc21

I have tried putting the console.log("main: " + sid) and add_CheckNow_Button(sid); lines inside a setTimeout() block, where the main output gets printed after the call_background_tab output, but I still see the main one as undefined, while call_background_tab returns a valid session id.

Why am I unable to get the value of rsp to the caller? Thanks.

0

There are 0 best solutions below