Home > Web Front-end > JS Tutorial > body text

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

Mary-Kate Olsen
Release: 2024-10-28 18:09:29
Original
134 people have browsed it

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'});
});
Copy after login

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'});
});
Copy after login

In the content script (content.js):

alert('Example:' + config);
Copy after login

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');
});
Copy after login

In content.js:

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

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!

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!