Home  >  Article  >  Web Front-end  >  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()`?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-29 12:18:29206browse

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:

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

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

<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, you can access these variables:

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

2. Setting Parameters After File Execution

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

<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, listen for these messages using chrome.runtime.onMessage and handle the message:

<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 Content Scripts Injected with `chrome.tabs.executeScript()`?. 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