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

How to Pass Parameters to Injected Content Scripts in Chrome Extensions?

Mary-Kate Olsen
Release: 2024-10-28 07:19:30
Original
573 people have browsed it

How to Pass Parameters to Injected Content Scripts in Chrome Extensions?

Passing Parameters to Injected Content Scripts Using chrome.tabs.executeScript()

When injecting content scripts using chrome.tabs.executeScript(tab.id, {file: "content.js"}), there is no direct way to pass parameters to the script. However, you can implement this functionality using two alternative methods:

Setting Parameters Before Execution

To define variables before executing the content script, nest chrome.tabs.executeScript calls as shown below:

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

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

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 content.js, access the variables using alert('Example:' config);.

Setting Parameters After Execution

To set parameters after execution, use 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, listen for messages using chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) { // Handle message });. The message will contain the parameter value.

The above is the detailed content of How to 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!