DEV Community

Kaushik Awala
Kaushik Awala

Posted on

Execute a function with arguments using chrome extension scripting API

Chrome introduced the new Manifest V3 towards a step in the direction of security, privacy, and performance as mentioned in the documentation here.

With this introduction of Manifest V3, there have been challenges in migrating from Manifest V2 to Manifest V3 which is beyond the scope of discussion in this article.

Along with number of features, the extensions using Manifest V3 also have functional changes introduced. Among many such changes, executeScript() is one. It has been moved from the Tabs API to the Scripting API. With the new Scripting API, extensions can register and unregister content scripts dynamically (at runtime, one can register and unregister content scripts as needed). Also, the extensions can now only execute script files and functions.

Here is how one can execute a function using the chrome extension's scripting API.

function greet(greeting) {
    console.log(`${greeting}, World!`);
 }

 chrome.scripting.executeScript({
      target: {tabId: tab.id},
      function: greet,
      args: ['Hello']
 });

 // Output: Hello, World!
Enter fullscreen mode Exit fullscreen mode

In the above code, we can notice that the property being used to pass the arguments to the function is args in Manifest V3.

Latest comments (0)