Javascript Chrome扩展将变量从popup.js传递到内容脚本

Javascript Chrome扩展将变量从popup.js传递到内容脚本,javascript,google-chrome,google-chrome-extension,Javascript,Google Chrome,Google Chrome Extension,我有popup.js脚本: function FireInjectionScript() { //Want to Pass this variable. var updateTextTo = document.getElementById('mat_no').value.trim() chrome.tabs.executeScript({ file: 'InjectionScript.js' }); } document.getElementB

我有popup.js脚本:

function FireInjectionScript() {
    //Want to Pass this variable.
    var updateTextTo = document.getElementById('mat_no').value.trim()
    chrome.tabs.executeScript({
        file: 'InjectionScript.js'
    }); 
}

document.getElementById('caseButton').addEventListener('click', FireInjectionScript);
在google和stackoverflow的前5页中,我几乎已经解决了所有的问题,但无法让这个简单的参数传递正常工作

已经试过了。很多问题都很老了。这在chrome中不可能了吗?我的最终目标是传递变量,然后从WebApi返回数据,根据传递的变量填写页面上的一些控件-我是不是找错了树了。非常感谢您的指导。

您可以使用将数据发送到注入脚本,但您需要选项卡Id

popup.js

function FireInjectionScript() {
    //Want to Pass this variable.
    var updateTextTo = document.getElementById('mat_no').value.trim();
    chrome.tabs.query({active: true, currentWindow: true}, tabs => {
        chrome.tabs.executeScript(tabs[0].id,{file: 'InjectionScript.js'},()=>{
            chrome.tabs.sendMessage(tabs[0].id,{myVar:updateTextTo});
        });
    }); 
}

document.getElementById('caseButton').addEventListener('click', FireInjectionScript);
chrome.runtime.onMessage.addListener(message=>{
    if (message.myVar) {
        //here you can access message.myVar
    }
});
InjectionScript.js

function FireInjectionScript() {
    //Want to Pass this variable.
    var updateTextTo = document.getElementById('mat_no').value.trim();
    chrome.tabs.query({active: true, currentWindow: true}, tabs => {
        chrome.tabs.executeScript(tabs[0].id,{file: 'InjectionScript.js'},()=>{
            chrome.tabs.sendMessage(tabs[0].id,{myVar:updateTextTo});
        });
    }); 
}

document.getElementById('caseButton').addEventListener('click', FireInjectionScript);
chrome.runtime.onMessage.addListener(message=>{
    if (message.myVar) {
        //here you can access message.myVar
    }
});

Nokonoko会试试的,我试过这个方法,但可能语法很旧。我在旧示例中使用的代码示例中一定有错误的语法