Chrome extension asynchronous messaging

I am currently working on a Chrome extension and I want to do the following.

content.js:

chrome.runtime.sendMessage({message: "Teszt", licenseKey: "XXXX-XXXX-XXXX-XXXX", data: "bolond"}, (response) => {
        alert(response.data);
});

background.js:

chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
    if(request) {

        const xhr = new XMLHttpRequest();
        xhr.open("GET", `https://api.hyper.co/v4/licenses/${request.licenseKey}`);
        xhr.setRequestHeader("Authorization", `Bearer publickey`)

        xhr.onload = () => {
            sendResponse({ sender: "background.js", data: (request.data+" response")  })
        }

        xhr.send();
    }
});

It doesn’t return anything, obviously because a request needs time to be done.
How can I make it async? Or at least how to make content.js to wait until background actually returns something?

Thank you in advance!

Source: Ask Javascript Questions

LEAVE A COMMENT