首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >chrome.scripting.executeScript不适用于background.js

chrome.scripting.executeScript不适用于background.js
EN

Stack Overflow用户
提问于 2022-05-06 07:24:11
回答 1查看 225关注 0票数 0

我正在开发一个chrome扩展,它将输入一些搜索条件,然后触发一个按钮来自动检索结果。由于不能立即响应结果,所以我使用background.js定期检查。

我有两个脚本文件: popup.js和background.js。非常奇怪的是,chrome.scripting.executeScript在popup.js中工作,但在background.js中不工作

background.js

代码语言:javascript
运行
复制
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

代码语言:javascript
运行
复制
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]
            });

        }
    });

});

代码语言:javascript
运行
复制
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

代码语言:javascript
运行
复制
{
    "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"
    ]
  }

我在这方面挣扎了两天,但没有任何进展,请帮忙。

EN

回答 1

Stack Overflow用户

发布于 2022-05-06 09:00:12

这是我真正的代码:

代码语言:javascript
运行
复制
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);

}

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72137629

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档