user1365732 user1365732 - 1 year ago 228
Javascript Question

Pass a parameter to a content script injected using chrome.tabs.executeScript()

How can I pass a parameter to the JavaScript in a content script file which is injected using:

chrome.tabs.executeScript(, {file: "content.js"});

Answer Source

There's not such a thing as "pass a parameter to a file".

What you can do is to either insert a content script before executing the file, or sending a message after inserting the file. I will show an example for these distinct methods below.

Set parameters before execution of the JS file

If you want to define some variables before inserting the file, just nest chrome.tabs.executeScript calls:

chrome.tabs.executeScript(, {
    code: 'var config = 1;'
}, function() {
    chrome.tabs.executeScript(, {file: 'content.js'});

If your variable is not as simple, then I recommend to use JSON.stringify to turn an object in a string:

var config = {somebigobject: 'complicated value'};
chrome.tabs.executeScript(, {
    code: 'var config = ' + JSON.stringify(config)
}, function() {
    chrome.tabs.executeScript(, {file: 'content.js'});

With the previous method, the variables can be used in content.js in the following way:

// content.js
alert('Example:' + config);

Set parameters after execution of the JS file

The previous method can be used to set parameters after the JS file. Instead of defining variables directly in the global scope, you can use the message passing API to pass parameters:

chrome.tabs.executeScript(, {file: 'content.js'}, function() {
    chrome.tabs.sendMessage(, 'whatever value; String, object, whatever');

In the content script (content.js), you can listen for these messages using the chrome.runtime.onMessage event, and handle the message:

chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) {
    // Handle message.
    // In this example, message === 'whatever value; String, object, whatever'
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download