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:
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);.
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!