Chrome extensions: execute script on current tab after receiving response from the api call (manifest v3)

33 views Asked by At

After clicking on a button on a default_popup html file, I want to execute API endpoint and inject (execute) a script with the API response to the current tab.

Executing a script without waiting for API response worked fine:

document.getElementById('myBtn').addEventListener('click', function() {
    
    chrome.tabs.query({ active: true, currentWindow: true}, function(activeTabs) {
        chrome.scripting
            .executeScript({
                target : {tabId : activeTabs[0].id},
                func : foo,
        })
        .then(() => finally());

        
    });
});

But when I want to the the same, just after the api response is fetched:

document.getElementById('myBtn').addEventListener('click', async function() {

    const response = await fetch("http://localhost:8888/get-data");
    const content = await response.json();

    chrome.tabs.query({ active: true, currentWindow: true}, function(activeTabs) {
        chrome.scripting
            .executeScript({
                target : {tabId : activeTabs[0].id},
                func : foo(content),
        })
        .then(() => finally());

        
    });
});

The script is not executed inside a current tab, but inside the popup itself, so waiting for response somehow messes up the chrome's injection logic. What am I doing wrong?

0

There are 0 answers