2

I have popup.js script:

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);

I have gone through pretty much every question in the the first 5 pages of google and stackoverflow and can't get this simple parameter pass working.

Have tried this, this, this. Many of the questions are rather old. Is this not possible in chrome anymore ? My ultimate goal is to pass the variable and then return data from a WebApi to fill out some controls on the page based on the variable passed - am I barking up the wrong tree. Any guidance is greatly appreciated.

bumble_bee_tuna
  • 3,533
  • 7
  • 43
  • 83

1 Answers1

5

You can use messaging to send the data to the injected script, but you need the tab 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);

InjectionScript.js

chrome.runtime.onMessage.addListener(message=>{
    if (message.myVar) {
        //here you can access message.myVar
    }
});
Iván Nokonoko
  • 4,888
  • 2
  • 19
  • 27