"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How Do I Pass Parameters to Content Scripts Injected with `chrome.tabs.executeScript()`?

How Do I Pass Parameters to Content Scripts Injected with `chrome.tabs.executeScript()`?

Published on 2024-11-07
Browse:874

How Do I Pass Parameters to Content Scripts Injected with `chrome.tabs.executeScript()`?

Passing Parameters to Content Scripts Injected with chrome.tabs.executeScript()

When injecting a content script file using chrome.tabs.executeScript({file: "content.js"}), a common question arises: how to pass parameters to the JavaScript within the content script file?

Parameter Passing Fallacy

It's important to clarify that you cannot directly pass parameters to a file. Instead, you have two options for achieving this functionality:

1. Setting Parameters Before File Execution

Nest chrome.tabs.executeScript calls to define variables before injecting the file:

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

For complex variables, consider using JSON.stringify to convert an object into a string:

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

In content.js, you can access these variables:

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

2. Setting Parameters After File Execution

Execute the file first, then use the message passing API to send parameters:

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

In content.js, listen for these messages using chrome.runtime.onMessage and handle the message:

chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) {
    // Handle message.
    // In this example, message === 'whatever value; String, object, whatever'
});
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3