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

How to Pass Parameters to Content Scripts in Chrome Extensions?

DDD
Release: 2024-10-28 12:47:02
Original
556 people have browsed it

How to Pass Parameters to Content Scripts in Chrome Extensions?

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>
Copy after login

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>
Copy after login

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>
Copy after login

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!

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
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!