When injecting a content script using chrome.tabs.executeScript(), one may encounter the need to pass parameters to the script. However, it's crucial to clarify that "passing a parameter to a file" is not an applicable concept.
Instead, there are two options to consider: setting parameters before or after script execution.
You can inject a content script with predefined parameters by nesting chrome.tabs.executeScript calls:
<code class="javascript">chrome.tabs.executeScript(tab.id, { code: 'var config = 1;' }, function() { chrome.tabs.executeScript(tab.id, {file: 'content.js'}); });</code>
For complex parameters, use JSON.stringify:
<code class="javascript">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'}); });</code>
In content.js:
<code class="javascript">// content.js alert('Example:' + config);</code>
Parameters can also be set after script execution using message passing:
<code class="javascript">chrome.tabs.executeScript(tab.id, {file: 'content.js'}, function() { chrome.tabs.sendMessage(tab.id, 'whatever value; String, object, whatever'); });</code>
In content.js:
<code class="javascript">chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) { // Handle message. // In this example, message === 'whatever value; String, object, whatever' });</code>
The above is the detailed content of How do I pass parameters to injected content scripts in Chrome extensions?. For more information, please follow other related articles on the PHP Chinese website!