Search code examples
javascriptfirefox-addonfirefox-addon-webextensions

How to send a variable with a addListener?


My popup script tries to get a variable from a content script:

browser.tabs.query({ active: true, currentWindow: true }, function (tabs) {
        //console.log("TryToCall");
        searchTerm = browser.tabs.sendMessage(tabs[0].id, { type: "getDoi" });
        console.log("received message: " + searchTerm);
        setButtons(searchTerm);
    });

The content script listens with:

function listener(message, sender, response) {
    //console.log("called");
    switch (message.type) {
        case "getDoi":
            console.log("I heard you. I send " + searchTerm)
            return searchTerm ;
        default:
            //console.error("Unrecognised message: " + message);
            return "X";
    }
}

The problem is: Instead of the string searchTerm (it is defined elsewhere and is correctly set in the listener as the console prints it out correctly) my popup gets [object Promise].

This is probably super simple, but I can't figure out how to make the popup to receive the string or convert the promise to the string.

Thanks in advance!


Solution

  • You can make this where you get the promise value.

    then is an object that launches after an promise has been resolved. In the same way if a promise has been rejected you can use .catch(res=>{}) to get an exception of some sort.

    In this case it would be

     searchTerm.then((res)=>{
          return res;
     })
    .then((res) => {
          console.log(res); //here is not a promise anymore, It will probably be an object that you can access
    })
    

    and then you will have your variable in the next then. In addition this will probably return you a json object, but if u want it as a text you can do

    searchTerm.then((res)=>{
          return res.path_to_string.text(); //Access the path of the res that contains the string you need and then convert it 
     })
    .then((res) => {
          console.log(res); //You will have a string containing the whole object.
    })
    

    I suggest you doccumenting more on Javascript Promise