Home > Web Front-end > JS Tutorial > 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
Release: 2024-10-29 12:18:29
Original
298 people have browsed it

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>
Copy after login

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>
Copy after login

In content.js, you can access these variables:

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

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template