Passing Parameters to Content Scripts with chrome.tabs.executeScript()
When utilizing chrome.tabs.executeScript() to inject content scripts, it may be necessary to pass parameters to the JavaScript within the script file.
Method 1: Set Parameters Before Script Execution
Instead of attempting to pass parameters directly to the file, consider injecting a content script prior to executing the target file. This method allows you to set variables in the global scope before the file is loaded:
<code class="javascript">chrome.tabs.executeScript(tab.id, { code: 'var config = 1;' }, function() { chrome.tabs.executeScript(tab.id, {file: 'content.js'}); });</code>
Method 2: Set Parameters After Script Execution
Another approach involves setting parameters after the script file has been executed using the message passing API:
<code class="javascript">chrome.tabs.executeScript(tab.id, {file: 'content.js'}, function() { chrome.tabs.sendMessage(tab.id, 'whatever value; String, object, whatever'); });</code>
In the content script (content.js), listen for these messages using chrome.runtime.onMessage, which allows you to handle and utilize the parameter:
<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 to Pass Parameters to Content Scripts in Chrome Extensions?. For more information, please follow other related articles on the PHP Chinese website!