Home  >  Article  >  Web Front-end  >  How to Pass Parameters to Injected Content Scripts in Chrome Extensions?

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

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-28 07:19:30574browse

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

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

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

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!

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