'chrome.scripting.executeScript doesn't work in background.js

i'm developing a chrome extension which will input some search conditions and then trigger a button to retrieve result automatically. Since the result can't be responded immediately, i use background.js to check periodically.

i have two script files: popup.js and background.js. It's very weird that, chrome.scripting.executeScript works in popup.js, but doesn't work in background.js

background.js

chrome.runtime.onMessage.addListener(
    function(request, sender, sendResponse) {
        console.log(request);
        console.log(sender.tab ?
                  "from a content script:" + sender.tab.url :
                  "from the extension");
        let current = request.current;
        // store current index in case extension crashed or closed
        chrome.storage.sync.set({current});
        console.log('current '+current); // i can see the output
        // check response periodically

        chrome.scripting.executeScript({
            target: { tabId: sender.tab.id},
            function: ()=>{console.log('hello world');}, // doesn't work
            args:[current]
        });
    }
);

popup.js

let uploadBtn = document.getElementById('upload');
uploadBtn.addEventListener("click", async()=> {
    let [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
    // should load data from csv
    // const ip=['192.168.1.1','192.168.1.2','192.168.1.3'];
    let csvInput = document.querySelector('input[type=file]');
    
    // alert(csvInput.files[0]);
    // alert(csvInput);
    Papa.parse(csvInput.files[0], {
        header:true,
        complete: function(results) {
            const INDEX = 0;
            let allIP = results.data;
            // store uploaded ip list in case extension crashed
            chrome.storage.sync.set({allIP});
            chrome.scripting.executeScript({
                target: { tabId: tab.id },
                function: sendRequest, // worked
                args:[INDEX,allIP]
            });

        }
    });

});

function sendRequest(index,allIP){
    const BAIDU_SEARCH_BOX = 'kw';
    const BAIDU_SEARCH_BTN = 'su';

    let textbox = document.getElementById(BAIDU_SEARCH_BOX);
    let btn = document.getElementById(BAIDU_SEARCH_BTN);
    textbox.value=allIP[index].IP地址;
    btn.click();
    //send message to background.js
    chrome.runtime.sendMessage({current: index}, function(response) {
      console.log(response);
      if(response.succeeded){
        let current = response.current;
        if(current > -1){
          sendRequest(current,ipList);
        } else{
          console.log('get all responses, start to analysis...');
        }
      }else{
        console.log('error'+response);
      }
    });
}

manifest.json

{
    "name": "test",
    "version": "0.1",
    "manifest_version": 3,
    "description": "Check IP info automatically",
    "action": {
        "default_popup": "popup.html"
    },
    "host_permissions":[
        "https://www.baidu.com/",
        "http://www.baidu.com/"
    ],
    "background":{
        "service_worker":"background.js"
    },
    "permissions": [
        "storage", 
        "activeTab", 
        "scripting",
        "tabs"
    ]
  }

i have struggled on this for two days, but no any progress, please help



Solution 1:[1]

here is my real code:

chrome.runtime.onMessage.addListener(
    function(request, sender, sendResponse) {
        console.log(sendResponse);
        console.log(sender.tab ?
                  "from a content script:" + sender.tab.url :
                  "from the extension");
        let current = request.current;
        // store current index in case extension crashed or closed
        chrome.storage.sync.set({current});
        console.log('current '+current);
        // check reponse periodlly

        chrome.scripting.executeScript({
            target: { tabId: sender.tab.id},
            function: checkResponse, //works
            args:[current,ipList]
        });
    }
);

function checkResponse(current,ipList){
    console.log('checkResponse executed ');
    const ONE_MINUTE = 1000 * 1;
    let interval = setInterval(()=>{
        let span = document.querySelector("span.page-item_M4MDr.pc");
        if(span){
            current++;
            chrome.storage.sync.set({current});
            clearInterval(interval);
            if(current >= ipList.length){
                // reach the end of ip list
                current = -1;
            }          
            // eval(callbackName)({succeeded:true ,next:current}); //doesn't work
            // since the response is completed, how to notify the message sender (popup.js)
        }
    },ONE_MINUTE);

}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 aqiao