tabs.executeScript – passing parameters and using libraries?

If you don’t want to use messaging then:

chrome.tabs.executeScript(tabId, {file: "jquery.js"}, function(){
    chrome.tabs.executeScript(tabId, {code: "var scriptOptions = {param1:'value1',param2:'value2'};"}, function(){
        chrome.tabs.executeScript(tabId, {file: "script.js"}, function(){
            //all injected
        });
    });
});

(jquery.js should be placed into extension folder). Script options will be available inside scriptOptions variable in the script.js.

With messaging it is just as easy:

chrome.tabs.executeScript(tabId, {file: "jquery.js"}, function(){
    chrome.tabs.executeScript(tabId, {file: "script.js"}, function(){
        chrome.tabs.sendMessage(tabId, {scriptOptions: {param1:'value1',param2:'value2'}}, function(){
            //all injected
        });
    });
});

You would need to add a request listener to script.js:

chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) {
    var scriptOptions = message.scriptOptions;
    console.log('param1', scriptOptions.param1);
    console.log('param2', scriptOptions.param2);
    doSomething(scriptOptions.param1, scriptOptions.param2);
});

Leave a Comment