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
Release: 2024-10-27 16:22:01
Original
379 people have browsed it

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

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

In content.js:

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

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

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

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!

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