Home >Web Front-end >JS Tutorial >How do I pass parameters to injected content scripts in Chrome extensions?

How do I pass parameters to injected content scripts in Chrome extensions?

Barbara Streisand
Barbara StreisandOriginal
2024-10-27 16:22:01356browse

How do I pass parameters to injected content scripts in Chrome extensions?

Passing Parameters to Injected Content Scripts

When injecting a content script using chrome.tabs.executeScript(), one may encounter the need to pass parameters to the script. However, it's crucial to clarify that "passing a parameter to a file" is not an applicable concept.

Instead, there are two options to consider: setting parameters before or after script execution.

Set Parameters Before Execution

You can inject a content script with predefined parameters by nesting chrome.tabs.executeScript calls:

<code class="javascript">chrome.tabs.executeScript(tab.id, {
    code: 'var config = 1;'
}, function() {
    chrome.tabs.executeScript(tab.id, {file: 'content.js'});
});</code>

For complex parameters, use JSON.stringify:

<code class="javascript">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'});
});</code>

In content.js:

<code class="javascript">// content.js
alert('Example:' + config);</code>

Set Parameters After Execution

Parameters can also be set after script execution using message passing:

<code class="javascript">chrome.tabs.executeScript(tab.id, {file: 'content.js'}, function() {
    chrome.tabs.sendMessage(tab.id, 'whatever value; String, object, whatever');
});</code>

In content.js:

<code class="javascript">chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) {
    // Handle message.
    // In this example, message === 'whatever value; String, object, whatever'
});</code>

The above is the detailed content of How do I pass parameters to injected content scripts in Chrome extensions?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn