0

I'm trying to send an array as a response from a background script to a content script, but it always comes back empty.

This is what I'm trying to do:

content-script

chrome.runtime.sendMessage(urlList, response => {
    console.log(response.matchList)
});

background script

chrome.runtime.onMessage.addListener(
    (urlList, sender, sendResponse) => {
        let matchList = []
        urlList.forEach(url => {
            chrome.history.search({text: url}, function(results) {
                if (results[0]) {
                    matchList.push(1)
                } else {
                    matchList.push(0)
                }
            });
        });
        sendResponse({matchList: matchList});
    }
)

It's probably a basic question, but it's my first time trying to build an extension for personal use. My problem is that the history search always happens last, so the array is returned empty.

deviance
  • 23
  • 4
  • Search is an asynchronous function. It doesn't execute until after forEach has finished. Use a promise to wait for it to do the callback. – John Dec 29 '20 at 21:05
  • I tried to look it up, but I'm not familiar with the sync-async concept, and the solutions I found are waiting for a value only not a function to finish. Can I ask how can you do that? I could analyze the solution to try understand it better. – deviance Dec 29 '20 at 21:44

0 Answers0