Home >Web Front-end >JS Tutorial >How to Pass Parameters to Injected Content Scripts with Chrome.tabs.executeScript()?

How to Pass Parameters to Injected Content Scripts with Chrome.tabs.executeScript()?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-28 18:09:29224browse

How to Pass Parameters to Injected Content Scripts with Chrome.tabs.executeScript()?

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

The chrome.tabs.executeScript() method allows for injecting JavaScript files into a tab's content. However, it does not provide a direct means of passing parameters to the injected script.

Method 1: Set Parameters Before Execution

One approach involves nesting chrome.tabs.executeScript() calls to define variables before executing the JavaScript file:

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

Complex variables can be converted to strings using JSON.stringify:

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 the content script (content.js):

alert('Example:' + config);

Method 2: Set Parameters After Execution

Alternatively, parameters can be passed after executing the JavaScript file using the message passing API:

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

In content.js:

chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) {
    // Handle message: message === 'whatever value; String, object, whatever'
});

The above is the detailed content of How to Pass Parameters to Injected Content Scripts 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